0

总是收到这个错误

  ValueError: invalid literal for int() with base 10: '3),'

从文本文件中读取看起来像这样:

[('cloud', 3), 
('words', 2), 
('code', 1), 
('word', 1), 
('appear', 1)]

如你所见,我试图用 word.replace() 替换一些东西

from pytagcloud import create_tag_image, make_tags
from pytagcloud.lang.counter import get_tag_counts


counts = []
with open("terms.txt") as FIN:
   for line in FIN:
  
       # Assume lines look like: word, number
       word,n = line.strip().split()
       word = word.replace(',', '')
       word = word.replace("'", "")
       word = word.replace("(", "")
       word = word.replace("[", "")
       word = word.replace(")", "")
       word = word.replace(" ", "")
       n = n.replace("'", "")
       n = n.replace(" ", "")

       counts.append([word,int(n.strip())])

       tags = make_tags(counts, maxsize=120)
create_tag_image(tags, 'cloud_large.png', size=(1200, 800), fontname='Crimson Text')

4

1 回答 1

1

发生这种情况是因为您没有替换n. 现在,从现有代码开始的最简单的解决方案(最小更改)是替换此行:

counts.append([word,int(n.strip())])

经过:

counts.append([word, int(n.strip(",)]"))])

当然,代码可以改进/简化,但需要更多的改变。这是一个示例(替换您提供的代码段中的这段代码):

with open("terms.txt") as FIN:
    for line in FIN:

        # Assume lines look like: word, number
        word,n = line.strip().split()
        word = word.replace(',', '')
        word = word.replace("'", "")
        word = word.replace("(", "")
        word = word.replace("[", "")
        word = word.replace(")", "")
        word = word.replace(" ", "")
        n = n.replace("'", "")
        n = n.replace(" ", "")

        counts.append([word,int(n.strip())])

经过:

with open("terms.txt") as FIN:
    for line in FIN:
        word, n = line.strip("[](), \r\n").split()
        counts.append([word.strip("',"), int(n.strip())])

有第三种形式,但使用eval(非常不鼓励);这就是您获取counts内容的方式(请注意,这里将是元组列表而不是列表列表):

counts = []
with open("terms.txt") as FIN:
    counts = eval(FIN.read())
于 2015-12-06T18:09:55.530 回答