逐字阅读文本文件用逗号分隔

时间:2014-01-01 08:56:38

标签: python list file-io

我想从文本文件(而不是csv文件)中创建用逗号分隔的单词列表。例如,我的文本文件包含以下行:

apple, Jan 2001, shelter, gate, goto, lottery, forest, pastery

我想将每个单词的列表列为:

['apple','Jan 2001','shelter','gate','goto','lottery','forest','pastery']

我所能做的就是用以下代码获取单词:

f = open('image.txt',"r")
line = f.readline()
for i in line:
    i.split(',')
    print i, 

6 个答案:

答案 0 :(得分:2)

>>> text = """apple, Jan 2001, shelter, gate, goto, lottery, forest, pastery"""
>>> 
>>> with open('in.txt','w') as fout:
...   fout.write(text)
... 
>>> with open('in.txt','r') as fin:
...   print fin.readline().split(', ')
... 
['apple', 'Jan 2001', 'shelter', 'gate', 'goto', 'lottery', 'forest', 'pastery']

答案 1 :(得分:1)

试试这个:

[i.strip() for i in line.split(',')]

演示:

>>> f = open('image.txt', 'r')
>>> line = f.readline()
>>> [i.strip() for i in line.split(',')]
['apple', 'Jan 2001', 'shelter', 'gate', 'goto', 'lottery', 'forest', 'pastery']

答案 2 :(得分:1)

这应该有效。也可以简化,但你会更好地理解它。

reading = open("textfiles\example.txt", "r")
allfileinfo = reading.read()
reading.close()

#Convert it to a list
allfileinfo = str(allfileinfo).replace(',', '", "')
#fix first and last symbols
nameforyourlist = '["' + allfileinfo  + '"]'

#The list is now created and named "nameforyourlist" and you can call items as example this way:
print(nameforyourlist[2])
print(nameforyourlist[69])

#or just print all the items as you tried in the code of your question.
for i in nameforyourlist:
  print i + "\n"

答案 3 :(得分:1)

输入:image.txt

apple, Jan 2001, shelter, gate, goto, lottery, forest, pastery
banana, Jul 2012, fig, olive

代码:

fp  = open('image.txt')
words= [word.strip() for line in fp.readlines() for word in line.split(',') if word.strip()]
print(", ".join(words)) # or `print(words)` if you want to print out `words` as a list

输出:

apple, Jan 2001, shelter, gate, goto, lottery, forest, pastery, banana, Jul 2012, fig, olive

答案 4 :(得分:0)

更改您的

f.readline() 

f.readlines() 

f.readline()将读取1行并返回一个String对象。迭代这将导致你的变量'i'有一个字符。角色没有名为split()的方法。你想要的是迭代一个字符串列表......

答案 5 :(得分:0)

content = '''apple, Jan 2001, shelter
gategoto, lottery, forest, pastery'''

[line.split(",") for line in content.split("\n")]