将字符串转换为十进制数值

huangapple go评论55阅读模式
英文:

Getting a decimal cast out of a string

问题

这是我在geeks for geeks上找到的用于创建列表的代码:

damages = []
def parse(d):
    dictionary = dict()
    # 移除花括号并将键值对拆分成列表
    pairs = d.strip('{}').split(', ')
    for i in pairs:
        pair = i.split(': ')
        # 移除键值对中的其他符号
        dictionary[pair[0].strip('\'\"')] = pair[1].strip('\'\"')
    return dictionary

try:
    geeky_file = open('TowerA/0-deg-DamagesStates.txt', 'rt')
    lines = geeky_file.read().split('\n')
    for l in lines:
        if l != '':
            dictionary = parse(l)
            damages.append(dictionary)
    geeky_file.close()
except:
    print("发生了意外情况!")

但是,为了运行下一个分析方法,"Decimal('0.7180868594')" 必须变为 Decimal('0.7180868594'),不带外部的字符串引号。

我尝试在def parse中剥离更多的引号,但没有帮助。有任何想法将不胜感激!

英文:

I am trying to read a txt file into a list of dictionaries, but since some of the entries are casted decimals (which is the output of a function I can't change), when I read them out of the txt file, they are double stringed.

This is the code I am using for creating the list that I found on geeks for geeks:

damages = []
def parse(d):
	dictionary = dict()
	# Removes curly braces and splits the pairs into a list
	pairs = d.strip('{}').split(', ')
	for i in pairs:
		pair = i.split(': ')
		# Other symbols from the key-value pair should be stripped.
		dictionary[pair[0].strip('\'\'\"\"\"\"')] = pair[1].strip('\'\'\"\"\'\'')
	return dictionary
try:
	geeky_file = open('TowerA/0-deg-DamagesStates.txt', 'rt')
	lines = geeky_file.read().split('\n')
	for l in lines:
		if l != '':
			dictionary = parse(l)
			damages.append(dictionary)
            #print(dictionary)
	geeky_file.close()
except:
	print("Something unexpected occurred!")

One line of the list this makes is:
{'DS_0': "Decimal('0.7180868594')", 'DS_1': '0', 'DS_2': '0', 'DS_3': "Decimal('0.2819131406')"}

But, in order to run the next analysis method, the
"Decimal('0.7180868594')"
, has to be
Decimal('0.7180868594') without the external string quotation marks.

I tried stripping more of the quotations marks in the def parse, but that didn't help anything.

Any ideas are greatly appreciated!

答案1

得分: 0

你可以手动拼接字符串,如下所示:

if value.startswith("Decimal('") and value.endswith("')"):
    value = Decimal(value[9:-2])

parse函数中。这是一种相当低效的解决方案,但希望对你的需求足够。

英文:

You can manually splice the string like so:

if value.startswith("Decimal('") and value.endswith("')"):
            value = Decimal(value[9:-2])

in parse. This is a pretty inefficient solution, but it should hopefully suffice for your purposes.

答案2

得分: 0

I am guessing that your 'next analysis method' involves using Decimal from the decimal library module; this takes a number as a string. If so then maybe this is useful:

You could use the eval function on the whole string:

n = eval("Decimal('0.7180868594')")

However, eval has specific security drawbacks which you can look up.

Better to extract the string and use that:

from decimal import Decimal
import re

s = "Decimal('0.7180868594')"

m = re.search(r"(\d+\.\d+)", s).group(1)

n = Decimal(m)
英文:

I am guessing that your 'next analysis method' involves using Decimal from the decimal library module; this takes a number as a string. If so then maybe this is useful:

You could use the eval function on the whole string:

n = eval("Decimal('0.7180868594')")

However, eval has specific security drawbacks which you can look up.

Better to extract the string and use that:

from decimal import Decimal
import re

s = "Decimal('0.7180868594')"

m = re.search(r"(\d+\.\d+)", s).group(1)

n = Decimal(m)

huangapple
  • 本文由 发表于 2023年7月18日 04:51:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707994.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定