Reading text file word by word separated by comma

梦想与她 提交于 2019-12-25 02:59:31

问题


I want to make a list of words separated by comma from a text file(not csv file). For example, my text file contains the line as:

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

I want to make a list of each word as:

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

All I could do is get the words as it is with the code below:

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

回答1:


Input: image.txt

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

Code:

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

Output:

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



回答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']



回答3:


Try this:

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

Demo:

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



回答4:


This should work. Can also be simplified but you will understand it better this way.

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"



回答5:


Change your

f.readline() 

to

f.readlines() 

f.readline() will read 1 line and return a String object. Iterating over this will cause your variable 'i' to have a character. A character does not have a method called split(). What you want is to iterate over a list of Strings instead ...




回答6:


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

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



来源:https://stackoverflow.com/questions/20867027/reading-text-file-word-by-word-separated-by-comma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!