简体   繁体   English

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

[英]Reading a list from a text file and swapping the items

I have a list in a text file in this format. 我在这种格式的文本文件中有一个列表。 The list has 1000's of entries like this and this is a small sample. 列表中有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'],
    ]

How do i read the list from the text file and get an output like this. 我如何从文本文件中读取列表并获得类似的输出。

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'],
]

I am able to read from the file and manipulate it as a string but how do i get it as a list. 我能够从文件中读取并将其作为字符串进行操作,但是如何获取它作为列表。 Breaking at the comma isn't an option since individual list items might have a comma. 不能使用逗号分隔,因为单个列表项可能带有逗号。

最简单的是列表理解:

new_items = [i[::-1] for i in myitems]
 newItems = [[b, a] for a, b in myitems]
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

if it really looks like that then 如果真的看起来像那样

 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 is very dangerous and should most likely not be used ... but this should work exec非常危险,因此很可能不被使用...但这应该可以工作

better solution 更好的解决方案

 #name yourfile with the myitems = [...] to items.py
 import items
 new_items = [reversed(l) for l in items.myitems]
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])

To read the file, use CSV since you state 'the individual items might have commas' 要读取文件,请使用CSV,因为您指出“单个项目可能带有逗号”

Example: 例:

if your file actually looks like this: 如果您的文件实际上看起来像这样:

'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'

Then this code reads the csv file and reverses the fields: 然后,此代码读取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'

Prints: 印刷品:

['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'] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM