【发布时间】:2017-06-04 12:09:17
【问题描述】:
所以我试图让我的程序从文本文件中打印出每个单词和标点符号的索引,当它出现时。我已经完成了那部分。 - 但问题是当我尝试使用这些索引位置重新创建带有标点符号的原始文本时。这是我的代码:
with open('newfiles.txt') as f:
s = f.read()
import re
#Splitting string into a list using regex and a capturing group:
matches = [x.strip() for x in re.split("([a-zA-Z]+)", s) if x not in ['',' ']]
print (matches)
d = {}
i = 1
list_with_positions = []
# the dictionary entries:
for match in matches:
if match not in d.keys():
d[match] = i
i+=1
list_with_positions.append(d[match])
print (list_with_positions)
file = open("newfiletwo.txt","w")
file.write (''.join(str(e) for e in list_with_positions))
file.close()
file = open("newfilethree.txt","w")
file.write(''.join(matches))
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(' '.join(sentence_seq))
正如我所说的第一部分工作正常,但后来我得到了错误:-
Traceback (most recent call last):
File "E:\Python\Indexes.py", line 33, in <module>
sentence_seq = [word_base[int(i)] for i in f_select.read().split()]
File "E:\Python\Indexes.py", line 33, in <listcomp>
sentence_seq = [word_base[int(i)] for i in f_select.read().split()]
IndexError: cannot fit 'int' into an index-sized integer
当程序通过'sentence_seq'向代码底部运行时会发生此错误
newfiles 是原始文本文件 - 一篇带有标点符号的多个句子的随机文章
list_with_positions 是每个单词在原文中出现的实际位置的列表
matches 是分隔的不同单词 - 如果文件中重复的单词(它们确实如此)匹配应该只有不同的单词。
有人知道我为什么会收到错误消息吗?
【问题讨论】:
-
您的
int必须太大,无法进行数组索引:stackoverflow.com/questions/4751725/… 可能重复(尚未结束问题) -
@Jean-FrançoisFabre 确实是因为我们正在将文本文件中的每个单词替换为整数(它的索引) - 可能大约 60-80 个单词。那么,这是否意味着克服这个问题的唯一方法是使用较短的文本文件?
-
在这里暗中刺伤。
file.write (''.join(str(e) for e in list_with_positions))写入的数据没有空格,这样当你读回它时,你的split()什么都不做,实际上你正在尝试按 80 位数字进行索引。 -
@roganjosh 哇,确实解决了很多问题,但最终输出是 - “他们说这是狗的生活”而不是“他们说这是狗的生活” - 是吗标点符号之间的空格错误?这也发生在句号上——我猜所有的标点符号都会像单词一样被处理,因为我分割原始文件的方式。你知道有什么方法可以让标点符号之间没有任何不必要的空格(因为你确实需要在句号之后而不是之前的空格。等等)
-
所以如果我创建一个包含
Welcome to Stack Overflow. It's fine that you didn't quite create an MCVE on your first question as otherwise it's quite interesting.的文件,那么我就设置好了? :)
标签: python list append runtime-error indexof