3 回答

TA貢獻1111條經(jīng)驗 獲得超0個贊
您想要拆分行字符串,而不是文件對象(您從中讀取字符串):
with open('data.txt','r') as myfile:
count = [word
for line in myfile
for word in line.split()
if word.lower().startswith('f')]
print(count)
列表理解中的連續(xù) for 循環(huán)有效地將文件扁平化為 (f-) 個單詞的列表。如果您對單詞本身不感興趣并且只想要計數(shù),您可以這樣做
with open('data.txt','r') as myfile:
# This works because bool inherits int, and True acts like 1, False like 0
count = sum(word.lower().startswith('f')
for line in myfile
for word in line.split())
print(count)
最后,如果您想要所有計數(shù),請使用Counter:
from collections import Counter
with open('data.txt','r') as myfile:
count = Counter(word.lower()[0]
for line in myfile
for word in line.split())
print(count['f'])

TA貢獻1890條經(jīng)驗 獲得超9個贊
你可以試試這個
Python 腳本
count = []
with open('data.txt','r') as myfile:
# remove len if you only need the words starting with `f`
count = len([word for word in myfile.read().replace("\n"," ").split(" ") if word.lower()[0] == "f"])
print(count)
輸入文件
Sample line inside a File which is a File
Another line in the file with the word File
輸出
4
在此處查看實際操作
你可以if word.lower()[0] == "f"用if word[0] == "f" or word[0] == "F"

TA貢獻1877條經(jīng)驗 獲得超6個贊
使用此輸入文件:
friday code floor funk
而這段代碼:
f_words = []
with open('words.txt') as myfile:
f_words = [word for word in myfile.read().split(" ") if word[0].lower() == 'f']
print(f_words)
我得到這個輸出:
['friday', 'floor', 'funk']
添加回答
舉報