简体   繁体   中英

Reading text file word by word separated by comma

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

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

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"

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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