【发布时间】:2020-03-31 12:46:59
【问题描述】:
在 Python3 中,从包含歌词/字幕/其他的现有 .txt 文件中, 我想做一个简单的列表(没有任何嵌套) 现有单词,没有空格或其他插入符号。
根据其他 StackExchange 请求,我做了这个
import csv
crimefile = open('she_loves_you.txt', 'r')
reader = csv.reader(crimefile)
allRows = list(reader) # result is a list with nested lists
ultimate = []
for i in allRows:
ultimate += i # result is a list with elements longer than one word
ultimate2 = []
for i in ultimate:
ultimate2 += i # result is a list with elements which are single letters
我希望的结果会是这样的
['She', 'loves', 'you', 'yeah', 'yeah', 'yeah', 'She', 'loves', 'you', ...]
================================================ ========================
有趣的是理解为什么代码(它作为上述代码的扩展运行):
import re
print (re.findall(r"[\w']+", ultimate))
带来以下错误:
Traceback (most recent call last):
File "4.4.4.csv.into.list.py", line 72, in <module>
print (re.findall(r"[\w']+", ultimate))
File "/usr/lib/python3.7/re.py", line 223, in findall
return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object
【问题讨论】:
-
re.findall 的第二个参数(本例中为ultimate)应该是一个字符串。您正在传递一个字符串列表。
标签: python python-3.x list data-conversion