【问题标题】:Python NLP: TypeError: not all arguments converted during string formattingPython NLP:TypeError:字符串格式化期间并非所有参数都转换了
【发布时间】:2014-10-05 01:03:22
【问题描述】:

我尝试了“Natural language processing with python”的代码,但是出现了类型错误。

import nltk
from nltk.corpus import brown

suffix_fdist = nltk.FreqDist()
for word in brown.words():
    word = word.lower()
    suffix_fdist.inc(word[-1:])
    suffix_fdist.inc(word[-2:])
    suffix_fdist.inc(word[-3:])
common_suffixes = suffix_fdist.items()[:100]

def pos_features(word):
    features = {}
    for suffix in common_suffixes:
        features['endswith(%s)' % suffix] = word.lower().endswith(suffix)
    return features
pos_features('people')

错误如下:

Traceback (most recent call last):
  File "/home/wanglan/javadevelop/TestPython/src/FirstModule.py", line 323, in <module>
    pos_features('people')
  File "/home/wanglan/javadevelop/TestPython/src/FirstModule.py", line 321, in pos_features
    features['endswith(%s)' % suffix] = word.lower().endswith(suffix)
TypeError: not all arguments converted during string formatting

谁能帮我找出我错在哪里?

【问题讨论】:

    标签: python nlp typeerror


    【解决方案1】:

    suffix 是一个元组,因为.items() 返回 (key,value) 元组。当你使用 % 时,如果右手边是一个元组,则这些值将被解包并按顺序替换为每个 % 格式。您得到的错误是抱怨元组的条目多于 % 格式。

    您可能只需要键(实际后缀),在这种情况下,您应该使用suffix[0].keys() 仅检索字典键。

    【讨论】:

    • 或者更好的是,改用.keys()
    • 抱歉我的错误操作不接受答案。这确实是一个很好的答案。有道理!非常感谢。我是 Python 新手。
    猜你喜欢
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2015-01-21
    • 1970-01-01
    • 2013-03-07
    • 2015-10-28
    相关资源
    最近更新 更多