【发布时间】:2017-06-05 20:54:14
【问题描述】:
这是我的代码:
import re
with open('newfiles.txt') as f:
s = f.read()
uniquelist = []
error = re.findall(r"[\w]+|[^\s\w]", (s))
for word in error:
if word not in uniquelist:
uniquelist.append(word)
print ("Here are the words in their first appearing index form: ")
my_indexes = ' '.join(str(uniquelist.index(word)+1) for word in error)
print (my_indexes)
file = open("newfiletwo.txt","w")
file.write (' '.join(str(my_indexes)))
file.close()
file = open("newfilethree.txt","w")
file.write(' '.join(uniquelist))
file.close()
word_base = None
with open('newfilethree.txt', 'rt') as f_base:
word_base = [None] + [z.strip() for z in f_base.read().split()]
sentence_seq = None
with open('newfiletwo.txt', 'rt') as f_select:
sentence_seq = [word_base[int(i)] for i in f_select.read().split()]
print(my_indexes)
print(' '.join(sentence_seq))
它接受一个文本文件并返回其中的单词和标点符号的位置(索引)。如果某事重复,则给出第一次遇到的位置索引。所以它,打印出索引。其次,在将分隔的单个单词保存为文件和索引列表之后,我尝试使用它们重新创建文本。所以最终的输出应该是带有标点符号的原始句子。但不幸的是,当程序运行最后一行代码时,我得到了这个错误:
Traceback (most recent call last):
File "E:\Python\Final.py", line 26, in <module>
print(' '.join(sentence_seq))
TypeError: sequence item 12: expected str instance, NoneType found
有谁知道问题出在哪里?
【问题讨论】:
-
好吧,
sentence_seq[12]是None... -
@thebjorn 你是什么意思?我对 python 很陌生
-
word_base[0]是None。因此,如果f_select.read().split()的任何元素是0,您将把None放入sentence_seq的那个元素中。但是join()期望所有列表元素都是字符串。 -
错误消息告诉您,在执行
print(' '.join(sentence_seq))时发生类型错误,因为在“序列项 12”(即sentence_seq[12])处,需要字符串时有一个None值反而。 Pythons' '.join(lst)要求lst的所有元素都是字符串类型。 -
@thebjorn 好的,让我稍微调整一下,现在正在处理代码
标签: python string list append indexof