【问题标题】:Python Pytagcloud osx ValueError invalid literal for int() with base 10: '3)Python Pytagcloud osx ValueError int() 的无效文字,基数为 10:'3)
【发布时间】:2015-12-07 02:18:45
【问题描述】:

总是出现这个错误

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

【问题讨论】:

    标签: python macos pytagcloud


    【解决方案1】:

    发生这种情况是因为您没有替换 n 中的所有非数字字符。现在,从现有代码开始的最简单的解决方案(最小更改)是替换这一行:

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

    作者:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 2019-08-16
      • 2023-03-09
      • 1970-01-01
      相关资源
      最近更新 更多