【问题标题】:IndexError: cannot fit 'int' into an index-sized integerIndexError:无法将“int”放入索引大小的整数中
【发布时间】: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


【解决方案1】:

您的方法的问题是使用''.join(),因为这将所有内容连接起来,没有空格。因此,当前的问题是您尝试然后 split() 什么实际上是一长串没有空格的数字;你得到的是一个包含 100 多位数字的单个值。因此,int 在尝试将其用作索引时会溢出一个巨大的数字。更大的问题是指数可能会达到两位数等;当数字没有空格连接时,您希望split() 怎么处理这个问题?

除此之外,您还没有正确处理标点符号。 ' '.join() 在尝试重构句子时同样无效,因为您有逗号、句号等。两边都有空格。

我已尽力坚持您当前的代码/方法(我认为在尝试了解问题的根源时更改整个方法没有巨大价值),但我仍然感到不安。我放弃了regex,也许这是需要的。我没有立即意识到有一个图书馆可以做这种事情,但几乎可以肯定肯定有更好的方法

import string

punctuation_list = set(string.punctuation) # Has to be treated differently

word_base = []
index_dict = {}
with open('newfiles.txt', 'r') as infile:
    raw_data = infile.read().split()
    for index, item in enumerate(raw_data):
        index_dict[item] = index
        word_base.append(item)

with open('newfiletwo.txt', 'w') as outfile1, open('newfilethree.txt', 'w') as outfile2:
    for item in word_base:
        outfile1.write(str(item) + ' ')
        outfile2.write(str(index_dict[item]) + ' ')

reconstructed = ''
with open('newfiletwo.txt', 'r') as infile1, open('newfilethree.txt', 'r') as infile2:
    indices = infile1.read().split()
    words = infile2.read().split()
    reconstructed = ''.join([item + ' ' if item in punctuation_list else ' ' + item + ' ' for item in word_base])

【讨论】:

  • 感谢很多人,感谢您的时间和技能,这真的很有帮助。 :-)
  • @TheWorldIn5 不客气,感觉这变得比原本应该的要困难得多;在你更广泛的目标中,我认为有一个图书馆。否则,处理标点符号总是会成为一个问题。我想知道 NLTK 是否可以提供帮助。
  • @TheWorldIn5 再次,不客气 :) 我想我错过了这个标记,请随时不接受我的答案,这让它保持开放......这意味着更多人们可能会回答。对于更一般的事情,我对自己的答案感兴趣。我的回答指出了主要问题,但我不喜欢它的处理方式;我们都可以从中学习
  • 为什么当我们打印'words'时,不是每个单词在文件中的位置,而是随机输出的数字,我手动检查然后输出的整数不代表每个单词的出现文本中的单词。万一你想知道我的文字在这里实际上是什么意思:“他们说这是狗的生活,但对于出生时没有前腿的埃斯特雷拉来说,她已经适应了袋鼠式的生活方式。秘鲁杂种狗没有”不要让残疾阻碍她,在 Tinga Maria 小镇获得名人地位。”
  • 您的解决方案看起来不错,几个 cmets:indices = [item for item in infile1.read().split()] => indices = infile1.read().split()(下一行相同)。 for item in word_base: if item in punctuation_list: reconstructed += item + ' ' else: reconstructed += ' ' + item + ' ' 也丑陋且表现不佳。我会写reconstructed = ''.join([item + ' ' if item in punctuation_list else ' ' + item + ' ' for item in word_base])。但这不是codereview-on-answers.stackexchange.com :)
猜你喜欢
  • 1970-01-01
  • 2018-08-21
  • 2019-12-15
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
  • 1970-01-01
相关资源
最近更新 更多