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

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

在Python中解析多行

在Python中解析多行

阿晨1998 2021-03-12 10:08:48
我目前正在學習Python,我需要編寫一個程序來確定一首詩中出現(xiàn)次數(shù)最多的單詞。使我困擾的問題是將一首詩的行解析成一個包含詩詞的單列表。當我解決它時,我將毫不費力地確定出現(xiàn)次數(shù)最多的單詞。我可以通過反復(fù)調(diào)用input()來訪問這首詩的行,最后一行包含三個字符###。所以,我寫道:while True:   y = input()   if y == "###":     break   y = y.lower()   y = y.split()并輸入:Here is a line like sparkling wineLine up now behind the cow###得到了結(jié)果:['here', 'is', 'a', 'line', 'like', 'sparkling', 'wine']['line', 'up', 'now', 'behind', 'the', 'cow']如果我嘗試調(diào)用y [0],則會得到:hereline如何在同一變量內(nèi)連接兩個列表,或者如何將每一行分配給不同的變量?
查看完整描述

2 回答

?
阿波羅的戰(zhàn)車

TA貢獻1862條經(jīng)驗 獲得超6個贊

words = []


while True:

   y = input()

   if y == "###":

     break

   words.extend(y.lower().split())


from collections import Counter

Counter(words).most_common(1)

整個代碼可以壓縮為以下一種格式:


Counter(y.lower() for x in iter(input, '###') for y in x.split()).most_common(1)

例如。


>>> sys.stdin = StringIO.StringIO("""Here is a line like sparkling wine

Line up now behind the cow

###""")

>>> Counter(y.lower() for x in iter(input, '###') for y in x.split()).most_common(1)

[('line', 2)]

由于每個請求,而沒有任何import小號


c = {} # stores counts

for line in iter(input, '###'):

    for word in line.lower().split():

        c[word] = c.get(word, 0) + 1 # gets count of word or 0 if doesn't exist


print(max(c, key=c.get)) # gets max key of c, based on val (count)

不必再次通過字典來查找最大單詞,請在進行操作時始終對其進行跟蹤:


c = {} # stores counts

max_word = None

for line in iter(input, '###'):

    for word in line.lower().split():

        c[word] = c.get(word, 0) + 1 # gets count of word or 0 if doesn't exist

        if max_word is None:

            max_word = word

        else:

            max_word = max(max_word, word, key=c.get) # max based on count       


print(max_word)


查看完整回答
反對 回復(fù) 2021-03-31
  • 2 回答
  • 0 關(guān)注
  • 186 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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