-15
add_numbers( "A1", "Element 560234 65952 6598881 20203256 2165883 659562 654981 24120 261240 31648948 23900 5512400 5512900 5612400 5612900" )

add_numbers( "A2", "Element 261240 31659 5612400 76803256 3165883 659863 654224 44120 261240 31648948 23900 3612200 9512900 5612400 5642924" )

add_numbers( "A3", "Element 841225 65952 2165883 63103256 2165883 644861 344966 84120 161540 31653948 23900 5513426 5518906 5682405 8682932" )

我想得到一个看起来像这样的字典(从上面的字符串是一个 txt 文件):

{A1: 560234, 65952,6598881, 20203256,2165883, 659562,....}

{A2: 261240 31659 5612400,....}

{A3: 841225 65952 2165883,....}

你有什么想法?我怎样才能做到这一点?谢谢你。

4

2 回答 2

6

现在了解您要处理此

add_numbers( "A1", "Element 560234 65952 6598881 20203256 2165883 659562 654981 24120 261240 31648948 23900 5512400 5512900 5612400 5612900" )

add_numbers( "A2", "Element 261240 31659 5612400 76803256 3165883 659863 654224 44120 261240 31648948 23900 3612200 9512900 5612400 5642924" )

add_numbers( "A3", "Element 841225 65952 2165883 63103256 2165883 644861 344966 84120 161540 31653948 23900 5513426 5518906 5682405 8682932" )

作为文本文件的文字内容到字典中,我会这样做:

import re # import regular expression module
d = {}

for line in open("myfile.txt", "r"):
    if not line.strip(): continue        # Skip blank lines
    data = re.findall('"([^"]*)"', line) # Extract text between double quotes

    if len(data) != 2: continue          # There were not exactly two pairs of double quotes, skip this line

    key, value = data
    d[key] = map(int, value.split()[1:]) # Remove "Element" and convert numbers to integers, add to dictionary

正则表达式的解释"([^"]*)"

  • "( )"匹配引号内的内容
  • [^"]*任何不包含 0 个或多个字符的字符串"

re.findall将在列表中返回结果。

编辑

我得到一个错误。ValueError:需要超过 1 个值才能解压

您的文件中必须有一行不包含两对双引号。我已经更新了上面的代码以忽略与您的规范不匹配的行。

于 2013-05-17T08:30:59.710 回答
5
import re,ast
def add_numbers(d,key,elements): #we pass in a reference to a dict, which we update
    d[key] = map(int,elements.split()[1:]) #Returns ["Element",...], so we select all but first [1:]
dic = {}
with open('file.txt') as f:
    for line in f:
        key,elems = ast.literal_eval(re.search(r'\((.+)\)',line).group(0))
        add_numbers(dic,key,elems)

生产

>>> 
{'A1': [560234, 65952, 6598881, 20203256, 2165883, 659562, 654981, 24120, 261240, 31648948, 23900, 5512400, 5512900, 5612400, 5612900], 'A3': [841225, 65952, 2165883, 63103256, 2165883, 644861, 344966, 84120, 161540, 31653948, 23900, 5513426, 5518906, 5682405, 8682932], 'A2': [261240, 31659, 5612400, 76803256, 3165883, 659863, 654224, 44120, 261240, 31648948, 23900, 3612200, 9512900, 5612400, 5642924]}
于 2013-05-17T08:27:09.510 回答