繁体   English   中英

逐字读取文本文件,以逗号分隔

[英]Reading text file word by word separated by comma

我想列出一个由文本文件(不是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, 
>>> 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']

尝试这个:

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

这应该工作。 也可以简化,但是您将通过这种方式更好地理解它。

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"

输入: 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

改变你的

f.readline() 

f.readlines() 

f.readline()将读取1行并返回String对象。 对此进行迭代将导致您的变量“ i”具有字符。 字符没有称为split()的方法。 您想要的是遍历一个字符串列表,而不是...

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

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

暂无
暂无

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

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