第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 split() 命令來計算 txt 中的特定單詞

如何使用 split() 命令來計算 txt 中的特定單詞

胡子哥哥 2022-06-14 16:21:10
我有一個txt文件,我想使用 list comprehension 和 command導(dǎo)出所有以'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'因此,有沒有其他方法可以使用列表理解和命令拆分以獲得所需的結(jié)果?
查看完整描述

3 回答

?
catspeake

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'])


查看完整回答
反對 回復(fù) 2022-06-14
?
當(dāng)年話下

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"


查看完整回答
反對 回復(fù) 2022-06-14
?
慕哥9229398

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']


查看完整回答
反對 回復(fù) 2022-06-14
  • 3 回答
  • 0 關(guān)注
  • 205 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號