題目: 尋找雙詞組 (Python)
編寫一個名為 find_bigrams
的函數,該函數接收一個句子或段落的字符串,并按順序返回其所有雙詞組的列表。
注意: 雙詞組是指連續的兩個單詞。
示例:
輸入:
sentence = """
Have free hours and love children?
Drive kids to school, soccer practice
and other activities.
"""
輸出:
def find_bigrams(sentence) ->[('have', 'free'),('free', 'hours'),('hours', 'and'),('and', 'love'),('love', 'children?'),('children?', 'drive'),('drive', 'kids'),('kids', 'to'),('to', 'school,'),('school,', 'soccer'),('soccer', 'practice'),('practice', 'and'),('and', 'other'),('other', 'activities.')]
答案
解題思路
解決這個問題的關鍵在于將輸入的句子或段落分割成單詞,并找到所有相鄰的單詞對。我們可以使用 Python 的字符串處理方法來實現這個功能。具體步驟如下:
- 移除輸入字符串的換行符,并將其轉換為小寫以確保一致性。
- 使用
split()
方法將字符串按空格分割成單詞列表。 - 使用列表推導式或循環生成所有相鄰的單詞對。
答案代碼
def find_bigrams(sentence):# 去掉換行符并將字符串轉換為小寫sentence = sentence.replace('\n', ' ').lower()# 按空格分割字符串以獲取單詞列表words = sentence.split()# 生成所有相鄰的單詞對bigrams = [(words[i], words[i + 1]) for i in range(len(words) - 1)]return bigrams# 示例輸入
sentence = """
Have free hours and love children?
Drive kids to school, soccer practice
and other activities.
"""# 打印輸出
print(find_bigrams(sentence))
sentence.replace('\n', ' ')
: 將字符串中的換行符替換為空格。sentence.lower()
: 將字符串轉換為小寫。sentence.split()
: 將字符串按空格分割成單詞列表。[(words[i], words[i + 1]) for i in range(len(words) - 1)]
: 使用列表推導式生成所有相鄰的單詞對。
更多詳細答案可關注公眾號查閱。