如何使用 split() 命令来计算 txt 中的特定单词

我有一个txt文件,我想使用 list comprehension 和 command导出所有以'F'或'f'split()开头的单词。


count = []

with open('data.txt','r') as myfile:

    count = [line for line in myfile.split() if (line[0]=='F' or line[0]=='f')]

print(count)

我采取以下错误


'_io.TextIOWrapper' 对象没有属性 'split'


因此,有没有其他方法可以使用列表理解和命令拆分以获得所需的结果?


胡子哥哥
浏览 183回答 3
3回答

catspeake

您想要拆分行字符串,而不是文件对象(您从中读取字符串):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 Counterwith open('data.txt','r') as myfile:    count = Counter(word.lower()[0]                    for line in myfile                    for word in line.split())print(count['f'])

当年话下

你可以试试这个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 FileAnother line in the file with the word File输出4在此处查看实际操作你可以if word.lower()[0] == "f"用if word[0] == "f" or word[0] == "F"

慕哥9229398

使用此输入文件: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']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python