Python: 检查列表每行的每个单词是否与字典中的键相同

0 投票
2 回答
2092 浏览
提问于 2025-04-18 12:44

这是我的基本代码。

for key in dictionary: #Here key is the actually variable defined in key:value pair
  for line in list:
    if key in line: 
        print key

我得到的错误信息是:

如果在行中找到关键字:

类型错误:转换为Unicode时出错:需要字符串或缓冲区,但找到了整数

我用这个来编码非ASCII值。

unicode = u"\xc3\x81"
encoded= unicode.encode('utf-8')

我注意到一些类型(key)是整数,所以我希望上面的代码能解决这个问题。

我查阅了很多资料,但仍然没有找到一种方法来检查字典中每个单词是否是关键字字符串。

另外,我被告知不要通过dictionary.keys()把字典变成列表,反之亦然。

2 个回答

0

假设你有这样的东西:

mydict = {"is": 1, "the": 2}

还有

list = ["Line is the first", "Line is the second",]

你可以试试:

>>> for line in list:
    for w in line.split(" "):
       print("Word", w, " in key list:", w in mydict.keys())

('Word', 'Line', ' in key list:', False)
('Word', 'is', ' in key list:', True)
('Word', 'the', ' in key list:', True)
('Word', 'first', ' in key list:', False)
('Word', 'Line', ' in key list:', False)
('Word', 'is', ' in key list:', True)
('Word', 'the', ' in key list:', True)
('Word', 'second', ' in key list:', False)
>>>

通常情况下,Python会帮你处理这些字符编码的问题,所以你可以直接比较这些字符串,不用太担心。

0

看起来你缺少了一些代码。很可能在你的代码中,有地方把一个unicode字符串和一个整数连接在了一起:

a = u"unicode str"
b = 5

print(a + b)

顺便提一下 - 关于这段代码:

unicode = u"\xc3\x81"
encoded= unicode.encode('utf-8')

这看起来不太对。你的第一行肯定不是unicode - 它可能是UTF-8格式的,你应该使用decode来处理。

unicode = "\xc3\x81"
encoded = unicode.decode('utf-8')
print encoded  # prints Á

撰写回答