1

我一直在尝试检查用户提交的字符串是否包含某个子字符串,并在打印回复时替换它们。

list_in_list = [["I", "you"], ["We", "Us"], ["Her", "Him"]]

我一直在使用以下代码来测试这些值是否作为调试回复:

print [row[0] for row in list_in_list] in reply

回复是用户输入的字符串

但是它返回此错误:

TypeError: 'in <string>' requires string as left operand, not list

我也无法弄清楚如何检索要替换的正确值。我正在考虑循环它

reply.replace(list_in_list[0][x], list_in_list[0][x]) 

其中 x = 执行的循环数量,但我对如何编码感到困惑。

4

2 回答 2

3

要测试是否有任何值,reply您可以执行类似的操作

print any(row[0] in reply for row in list_in_list)

替换中的所有值reply

for row in list_in_list:
    reply = reply.replace(row[0], row[1])
print reply

回应您的评论

reply = "This is a test I We Her"
#rw = replace_with
rw = {"I":"You", "We":"Us", "Her":"Him"}

reply = " ".join([rw[word] if word in rw else word for word in reply.split()])

print reply

根据您输入的复杂程度,您可能会考虑使用正则表达式或研究自然语言处理(用于处理收缩等)。

于 2013-04-14T00:50:37.100 回答
1

你的意思是这样的:

print [row[0] for row in list_in_list if row[0] in reply]

这将为您提供第一列中的值,但前提是它们是in reply. 例如:

>>> list_in_list = [["I", "you"], ["We", "Us"], ["Her", "Him"]]
>>> reply = "I like cake"
>>> print [row[0] for row in list_in_list if row[0] in reply]
['I']
>>> reply = "We met Her yesterday"
>>> print [row[0] for row in list_in_list if row[0] in reply]
['We', 'Her']
于 2013-04-14T00:41:21.603 回答