[英]Reading comma-separated words into pandas
I have a file filled with words like so : 我有一个像这样的文件:
words.txt 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? 如何使用Pandas读取此文件? My ultimate goal would be a series that contained (A, B, C, D, E. . .O)
我的最终目标将是一个包含(A,B,C,D,E..O)的系列
read_csv seems geared towards a table. read_csv似乎适合表。
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. 您不需要单独的pandas库,只需使用
csv
模块即可。 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. skipinitialspace
是跳过定界符之后的空白,它似乎在您的csv中。
Example/Demo - 示例/演示-
My a.csv
- 我的
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.