I have a file filled with words like so :
words.txt
"A", "B", "C", "D", "E",
"F", "G", "H", "I", "J",
"K", "L", "M", "N", "O"
How can I read this file using Pandas? My ultimate goal would be a series that contained (A, B, C, D, E. . .O)
read_csv seems geared towards a table.
I managed to accomplish this using
words = list(pd.read_csv('words.txt').columns)
But this is so ugly. I'm sure there's a better way.
Thank you!
This would be an answer
list = ["A", "B", "C", "D", "E","F", "G", "H", "I", "J","K", "L", "M", "N", "O"]
print(list)
Output:
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']
使用纯python,您可以执行以下操作来建立列表:
words = [word.strip() for line in open("words.txt") for word in line.split(",") if word]
You do not need pandas library for this alone, you can simply use the csv
module for this. Example -
import csv
with open('<csvfile>','r') as f:
reader = csv.reader(f,skipinitialspace=True)
words = next(reader)
skipinitialspace
is to skip the whitespace after the delimiter , which seems to be there in your csv.
Example/Demo -
My a.csv
-
"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O"
Code and result -
>>> import csv
>>> with open('a.csv','r') as f:
... reader = csv.reader(f,skipinitialspace=True)
... words = next(reader)
...
>>> words
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']
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.