Python Pytagcloud osx ValueError对于带有基数10的int()的无效文字:' 3)

时间:2015-12-06 16:42:19

标签: python macos pytagcloud

始终收到此错误

  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')




1 个答案:

答案 0 :(得分: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())