在Python3中,从包含lyric/subtitle/other的现有.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
下面是我在这个问题上所做工作的全部成果
试试这个:
错误消息完全清楚
"expected string or bytes-like object"
。 这意味着您的ultimate
应该转换为字符串(str)
,当您检查ultimate
的type
时,它是list
对象就你而言
相关问题 更多 >
编程相关推荐