![](/img/trans.png)
[英]How do I loop over a string and add words that start with a certain letter to an empty list?
[英]Find how many words start with certain letter in a list
我試圖從單獨的文本文件中輸出列表中以字母'a'
開頭'a'
單詞總數。 我正在尋找這樣的輸出。
35 words start with a letter 'a'.
但是,我正在輸出以'a'
開頭的所有單詞,而不是當前代碼中的全部單詞。 我是否應該使用for循環以外的其他方式?
到目前為止,這是我嘗試過的:
wordsFile = open("words.txt", 'r')
words = wordsFile.read()
wordsFile.close()
wordList = words.split()
print("Words:",len(wordList)) # prints number of words in the file.
a_words = 0
for a_words in wordList:
if a_words[0]=='a':
print(a_words, "start with the letter 'a'.")
到目前為止,我得到的輸出是:
Words: 334
abate start with the letter 'a'.
aberrant start with the letter 'a'.
abeyance start with the letter 'a'.
等等。
你可以用替換此sum
通話中你喂1
中的每一個字wordList
是開頭a
:
print(sum(1 for w in wordList if w.startswith('a')), 'start with the letter "a"')
如果您使用startswith
返回的布爾值來代替,則可以進一步縮小,因為在這些情況下, True
被視為1
,因此效果是相同的:
print(sum(w.startswith('a') for w in a), 'start with the letter "a"')
使用當前的方法,您無需求和,僅打印任何匹配的單詞。 另外,您在迭代時將a_word
從一個int
重命名為列表的內容。
另外,您可以使用startswith(character)
來代替第一個字符,而不用使用a_word[0]
來檢查第一個字符,該命令具有相同的效果並且可讀性更高。
您在每次迭代中都使用a_words
作為單詞的值,並且缺少計數器。 如果我們更改for循環以將words
作為值並為計數器保留a_words
,則每次通過標准時,我們都可以遞增計數器。 您可以將a_words
更改為wordCount
或其他通用名稱,以使其對其他字母更易於攜帶和友好。
a_words = 0
for words in wordList:
if words[0]=='a':
a_words += 1
print(a_words, "start with the letter 'a'.")
sum(generator)
是一種可行的方法,但是出於完整性考慮,您可能希望通過列表理解來實現(也許可讀性更高,或者您想要對以等開頭的單詞進行處理)。
words_starting_with_a = [word for word in word_list if word.startswith('a')]
之后,您可以使用內置的len
來檢索新列表的長度。
print(len(words_starting_with_a), "words start with a letter 'a'")
使用re.findall
函數的簡單替代解決方案(不拆分文本和for
循環):
import re
...
words = wordsFile.read()
...
total = len(re.findall(r'\ba\w+?\b', words))
print('Total number of words that start with a letter "a" : ', total)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.