从文本文件中读取列表并交换项目

时间:2012-08-30 23:08:17

标签: python

我在这种格式的文本文件中有一个列表。该列表有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'],
]

我能够从文件中读取并将其作为字符串进行操作,但我如何将其作为列表获取。由于单个列表项可能包含逗号,因此不能选择逗号。

6 个答案:

答案 0 :(得分:5)

最简单的是列表理解:

new_items = [i[::-1] for i in myitems]

答案 1 :(得分:3)

 newItems = [[b, a] for a, b in myitems]

答案 2 :(得分: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

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

答案 4 :(得分: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])

答案 5 :(得分: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']