0

我在这种格式的文本文件中有一个列表。该列表有 1000 个这样的条目,这是一个小样本。

myitems =[
      ['some text, A', '12345'],
      ['place name 1', 'AAA'],
      ['some text, A', '12345'],
      ['some text', '12345'],
      ['some text CC', 'wwww'],
      ['new text', '12345'],
      ['other text, A', '12345'],
    ]

我如何从文本文件中读取列表并获得这样的输出。

newItems = [
  ['12345', 'some text, A'],
  ['AAA', 'place name 1'],
  ['12345', 'some text, A'],
  ['12345', 'some text'],
  ['wwww', 'some text CC'],
  ['12345', 'new text'],
  ['12345', 'other text, A'],
]

我能够从文件中读取并将其作为字符串进行操作,但我如何将其作为列表获取。不能以逗号分隔,因为单个列表项可能有逗号。

4

6 回答 6

5

最简单的是列表理解:

new_items = [i[::-1] for i in myitems]
于 2012-08-30T23:19:44.410 回答
3
 newItems = [[b, a] for a, b in myitems]
于 2012-08-30T23:29:31.750 回答
1
import sys

# Reading your file (the path has been passed in argument) and storing each lines in the array called "input"
input = []
with open(sys.argv[1], 'r') as all_lines:
    for line in all_lines:
        if line:
            input.append(line)

# Creating your array "newItems"
for j in input: 
    print j

newItems = []
if len(input)>2:
    for i in range(1, len(input)-1):
        # Getting content inside brackets. Ex: {{ 'some text, A', '12345' }}
        my_str = input[i].split("[")[1].split("]")[0]
        my_elements = my_str.split("'")

        # Appending elements
        newItems.append([my_elements[1], my_elements[3]])

print  newItems
于 2012-08-30T23:31:33.040 回答
0

要读取文件,请使用 CSV,因为您声明“个别项目可能有逗号”

例子:

如果您的文件实际上如下所示:

'some text, A','12345'
'place name 1','AAA'
'some text, A','12345' 
'some text','12345'
'some text CC','wwww' 
'new text','12345'
'other text, A','12345'

然后此代码读取 csv 文件并反转字段:

import csv

with open('test.csv','rb') as csvIN:
    for row in csv.reader(csvIN, delimiter=',',quotechar="'"):
        print row
        row=row[::-1]
        print '==>',row,'\n'

印刷:

['some text, A', '12345']
==> ['12345', 'some text, A'] 

['place name 1', 'AAA']
==> ['AAA', 'place name 1'] 

['some text, A', '12345 ']
==> ['12345 ', 'some text, A'] 

['some text', '12345']
==> ['12345', 'some text'] 

['some text CC', 'wwww ']
==> ['wwww ', 'some text CC'] 

['new text', '12345']
==> ['12345', 'new text'] 

['other text, A', '12345']
==> ['12345', 'other text, A'] 
于 2012-08-31T01:13:06.233 回答
0

如果它真的看起来像那样

 with open(my_file) as f:
   exec(f.read()) #read in the text and evaluate it in python creating myitems variable
   my_list = [reversed(l) for l in myitems]

exec 非常危险,很可能不应该使用......但这应该可以

更好的解决方案

 #name yourfile with the myitems = [...] to items.py
 import items
 new_items = [reversed(l) for l in items.myitems]
于 2012-08-30T23:16:50.547 回答
0
import re

f = open('myfile.txt', 'r')
newItems = []
for line in f:
    foo = re.search("\'(.*)\'.*\'(.*)\'", line) #we assume the values are 
                                                #in single quotes
    if foo is not None:
        a, b = foo.groups()
        newItems.append([b, a])
于 2012-08-30T23:39:53.187 回答