Python - 字符串分割线

时间:2013-05-17 08:17:42

标签: python string split

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,....}

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

2 个答案:

答案 0 :(得分: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]}

答案 1 :(得分:5)

立即了解您要处理此

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个值

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