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

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

Getting a decimal cast out of a string

问题

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

  1. damages = []
  2. def parse(d):
  3. dictionary = dict()
  4. # 移除花括号并将键值对拆分成列表
  5. pairs = d.strip('{}').split(', ')
  6. for i in pairs:
  7. pair = i.split(': ')
  8. # 移除键值对中的其他符号
  9. dictionary[pair[0].strip('\'\"')] = pair[1].strip('\'\"')
  10. return dictionary
  11. try:
  12. geeky_file = open('TowerA/0-deg-DamagesStates.txt', 'rt')
  13. lines = geeky_file.read().split('\n')
  14. for l in lines:
  15. if l != '':
  16. dictionary = parse(l)
  17. damages.append(dictionary)
  18. geeky_file.close()
  19. except:
  20. 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:

  1. damages = []
  2. def parse(d):
  3. dictionary = dict()
  4. # Removes curly braces and splits the pairs into a list
  5. pairs = d.strip('{}').split(', ')
  6. for i in pairs:
  7. pair = i.split(': ')
  8. # Other symbols from the key-value pair should be stripped.
  9. dictionary[pair[0].strip('\'\'\"\"\"\"')] = pair[1].strip('\'\'\"\"\'\'')
  10. return dictionary
  11. try:
  12. geeky_file = open('TowerA/0-deg-DamagesStates.txt', 'rt')
  13. lines = geeky_file.read().split('\n')
  14. for l in lines:
  15. if l != '':
  16. dictionary = parse(l)
  17. damages.append(dictionary)
  18. #print(dictionary)
  19. geeky_file.close()
  20. except:
  21. 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

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

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

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

英文:

You can manually splice the string like so:

  1. if value.startswith("Decimal('") and value.endswith("')"):
  2. 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:

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

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

Better to extract the string and use that:

  1. from decimal import Decimal
  2. import re
  3. s = "Decimal('0.7180868594')"
  4. m = re.search(r"(\d+\.\d+)", s).group(1)
  5. 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:

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

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

Better to extract the string and use that:

  1. from decimal import Decimal
  2. import re
  3. s = "Decimal('0.7180868594')"
  4. m = re.search(r"(\d+\.\d+)", s).group(1)
  5. 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:

确定