3 回答
TA贡献1111条经验 获得超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)
列表理解中的连续 for 循环有效地将文件扁平化为 (f-) 个单词的列表。如果您对单词本身不感兴趣并且只想要计数,您可以这样做
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)
最后,如果您想要所有计数,请使用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条经验 获得超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条经验 获得超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']
添加回答
举报