我有一个list
{tuples
和一些类似的数据:[('word1','sentence1'),('word2','sentence1'),('word3','sentence1') ...]
,我循环每个元组,得到每个单词和句子,如下所示:
for collection in tup:
qword = collection[0]
sentence = collection[1]
到目前为止,一切顺利。我需要删除句子中的每个单词,所以我这样做:
q_sentence_split = sentence.split()
new_sentence_split = [word.replace(q_word, '.....') for word in q_sentence_split]
new_sentence = ' '.join(sentence_split)
但是这并没有给我我所需要的,因为它从q_senetnce_split
中的每个单词中删除元组的word
字符,但我需要的只是单词,而不是将单词的字符与句子中每个单词的字符进行比较
我尝试将if放在for word in q_sentence_split
后面,如下所示:
new_sentence_split = [word.replace(q_word, '.....') for word in q_sentence_split if word == qword]
但这只是删除了句子中的每个单词,所以我不知道我的代码有什么问题
试试这个:
输出:
我故意把
word1
放在第三句说明:
首先我们迭代
lst
,它在每次迭代中给我们一个元组,我们用word, sentence
解压它在分割
sentence
之后,它成为一个列表,即['The', 'word1', 'is', 'in', 'this', 'sentence']
(在第一次迭代中)然后我们再次遍历这个列表,它给出了单个单词,我们所要做的就是检查我们的
word
是否在这些单词中。如果它不在那里,那就是我们想要的最后我们做
' '.join()
来造句以下是您可以做的:
相关问题 更多 >
编程相关推荐