Python NLP:TypeError:在字符串格式化过程中未转换所有参数
我尝试了“使用python进行自然语言处理”的代码,但出现了一个类型错误Python NLP:TypeError:在字符串格式化过程中未转换所有参数,python,nlp,typeerror,Python,Nlp,Typeerror,我尝试了“使用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(wor
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
回溯(最近一次呼叫最后一次):
文件“/home/wanglan/javadevelope/TestPython/src/FirstModule.py”,第323行,在
pos_功能(“人”)
文件“/home/wanglan/javadevelope/TestPython/src/FirstModule.py”,第321行,在pos_功能中
特征['endswith(%s)'%后缀]=word.lower().endswith(后缀)
TypeError:在字符串格式化过程中并非所有参数都已转换
有人能帮我找出哪里错了吗?
后缀是一个元组,因为.items()
返回(键、值)元组。当您使用%时,如果右侧是元组,则将按顺序解包并替换每个%格式的值。您得到的错误是,元组的条目多于%formats
您可能只需要键(实际的后缀),在这种情况下,您应该使用后缀[0]
,或.keys()
仅检索字典键 或者更好的方法是,只需使用.keys()
即可。很抱歉,我的错误操作无法接受答案。这确实是一个很好的答案。有道理!非常感谢。我是Python的新手。