这是我的密码
import re
with open('newfiles.txt') as f:
k = f.read()
p = re.compile(r'[\w\:\-\.\,\']+|[^[\w\:\-\.\'\,]\s]')
originaltext = p.findall(k)
uniquelist = []
for word in originaltext:
if word not in uniquelist:
uniquelist.append(word)
indexes = ' '.join(str(uniquelist.index(word)+1) for word in originaltext)
n = p.findall(indexes)
file = open("newfiletwo.txt","w")
file.write (' '.join(str(e) for e in n))
file.close()
file = open("newfilethree.txt","w")
file.write(' '.join(uniquelist))
file.close()
with open('newfiletwo.txt') as f:
indexess = f.read()
with open('newfilethree.txt') as f:
differentwords = f.read()
differentwords = p.findall(differentwords)
indexess = [uniquelist.index(word) for word in originaltext]
for word in originaltext:
if not word in differentwords:
differentwords.append(word)
i = differentwords.index(word)
indexess.append(i)
s = "" # the reconstructed sentence
for i in indexess:
s = s + differentwords[i] + " "
print(s)
程序基本上获取一个外部文本文件,返回其位置的索引(如果有任何单词重复,则获取第一个位置),然后将这些位置保存为一个外部文件。在这样做的同时,我分割了文本文件,包括分割标点符号,并将文件中出现的不同单词和标点符号保存为外部文件。现在,对于困难的部分,使用这两个外部文件-索引和不同的分隔词,我尝试重新创建原始文本文件,包括标点符号。但是标题中显示的错误发生了:
Traceback (most recent call last):
File "E:\Python\Index.py", line 31, in <module>
s = s + differentwords[i] + " "
IndexError: list index out of range
我不想听起来粗鲁,但我是一个初学者,请尝试用一种简单的方式尽可能少的改变,因为这是我自己创造的。你们可能知道一个短得多的方法来做这件事,但这是我能处理的简单程度,代码的长度证明了这一点。我试图缩短原始文本文件,但那证明没有用。有人知道为什么会发生错误以及如何修复它吗?我现在不是在寻找效率,也许再学习几个月后,但最简单(我不介意太长)的答案将是最好的。抱歉,我重复了很多次:-)
“newfiles”-一堆带有标点符号的句子
更新
代码不显示错误,但打印两次原始语句。由于删除了第23行上的+1,错误已消失。有人知道为什么输出会重复两次吗?你知道吗
问题是,你如何限定什么词是,什么词不是。例如,逗号是单词的一部分吗?在你的情况下,这是没有提到这样,而它也不是一个分隔符。所以你会得到一个单独的单词逗号,或点,等等。我无法访问您的输入,因此我只能提供示例:
p = re.compile(r'[\w\:\-\.\,]+|[^[\w\:\-\.\,]\s]')
有一点-在本例中:“Word”、“Word”、“Word”、“Word.”、“Word”都是独立的词。因为dot和coma是单词的一部分。你不能吃了蛋糕就吃了。为了解决这个问题。。。如果分离前有空格,则需要存储信息。你知道吗
更新: 哦,是的。双倍输出。存储在中间的文件-正常。所以在那之后有些东西被归档了。看这两行:
i = differentwords.index(word) indexess.append(i)
它们必须在前面的if语句中。你知道吗相关问题 更多 >
编程相关推荐