📌  相关文章
📜  Python程序删除两个字符串中常见的单词(1)

📅  最后修改于: 2023-12-03 15:19:34.854000             🧑  作者: Mango

Python程序删除两个字符串中常见的单词

本文将介绍如何使用Python编写一个程序,以从两个字符串中删除常见的单词。我们将首先解释程序的功能,然后提供完整的代码和用法示例。

功能说明

该程序接受两个字符串作为输入,并在这两个字符串中删除那些出现在常见单词列表中的单词。常见单词列表是一个预先定义好的单词集合,您可以根据自己的需要进行修改。

删除单词后,程序将返回更新后的两个字符串,并且每个字符串中所删除的单词都会用空格进行分隔。

代码实现
def remove_common_words(string1, string2):
    common_words = ["is", "the", "and", "a", "to", "in"]  # 常见单词列表
    words1 = string1.split()
    words2 = string2.split()
    
    # 删除string1中的常见单词
    filtered_words1 = [word for word in words1 if word.lower() not in common_words]
    updated_string1 = ' '.join(filtered_words1)
    
    # 删除string2中的常见单词
    filtered_words2 = [word for word in words2 if word.lower() not in common_words]
    updated_string2 = ' '.join(filtered_words2)
    
    return updated_string1, updated_string2
用法示例
string1 = "This is a sample sentence."
string2 = "The quick brown fox jumps over the lazy dog."

updated_string1, updated_string2 = remove_common_words(string1, string2)

print("Updated String 1:", updated_string1)
print("Updated String 2:", updated_string2)

输出:

Updated String 1: This sample sentence.
Updated String 2: quick brown fox jumps over lazy dog.

如示例所示,程序成功删除了常见的单词,并返回了更新后的两个字符串。

希望本文对你理解如何使用Python编写一个程序来删除两个字符串中常见的单词有所帮助!