你的这部分代码看起来是良好
for line in new_file:
text = [line.strip() for line in line.split(' ')]
但如果你正在做以下
for line in new_file:
text = [line.strip() for line in line.split(' ')]
number = text[0], punc = text[1], alpha = text[2]
你可以在你的文件下面跑进problems..take例如线
"hello world"
如果你分割这一行,你将会得到一个像[“hello”,“world”]这样的列表。 ns两个元素。
现在,如果您分配这个结果像text=["hello", "world"]
,你把这个结果在一个变量一样
alpha = text[2]
你一定会收到List index out of range.
..Why?
因为文本[2]不存在!
某些行可能包含少于3个字(就像这个例子)
修改你的方法
尝试使用字典方法
alpha={"alphabet":[]}
numb={"alphabet":[]}
punc={"punctuation":[]}
..iterate通过文件并使用列表理解选择所有的标点符号,字母等,并将其添加到各自的字典元素......如果您在发布修改后的代码时遇到问题
编辑工作的例子我将如何解决这个
让说我有一个NEW_FILE文件命名,并具有以下
hello my name is repzERO
AND THIS IS my age: 100 years
Python脚本我试过
import re
new_file=open("new_file","r")
alpha={"alphabet":[]}
numb={"number":[]}
punc={"punctuation":[]}
all_punctuation=""
for line in new_file:
alpha["alphabet"]+=[c for c in line if re.search("[a-zA-Z ]",c)]
numb["number"]+=[c for c in line if re.search("[0-9]",c)]
punc["punctuation"]+=[c for c in line if re.search("[^\w\s]",c)]
print(alpha)
print(numb)
print(punc)
内容
输出
{'alphabet': ['h', 'e', 'l', 'l', 'o', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'r', 'e', 'p', 'z', 'E', 'R', 'O', 'A', 'N', 'D', ' ', 'T', 'H', 'I', 'S', ' ', 'I', 'S', ' ', 'm', 'y', ' ', 'a', 'g', 'e', ' ', ' ', 'y', 'e', 'a', 'r', 's']}
{'number': ['1', '0', '0']}
{'punctuation': [':']}
你可以添加你的代码质疑吗? – Kasramvd
好的,我已经在问题中输入了我的代码! – Luke
@Luke请用你的代码编辑这个问题 –