Python3:查找出现次数最多的单词,无需使用导入、计数器或字典,只需使用简单的工具,如.split() ;及.下()

Python3:查找出现次数最多的单词,无需使用导入、计数器或字典,只需使用简单的工具,如.split() ;及.下(),python,Python,我目前正在学习Python,并试图解决一个免费的教程问题 问题是 一位作家正在写他们的新诗《图灵与机器》。他们雇佣你来确定出现次数最多的单词。您可以通过反复调用input()来访问这首诗的行,最后一行包含三个字符###。所有行由单个空格分隔的单词组成;没有数字或标点符号。将所有单词转换为小写,并打印出现次数最多的单词(我们保证不会出现平局)。 例如,如果输入是 这是一条像起泡酒一样的线 快排好队,否则就排在最后 ### 那么输出应该是 线 因为它出现两次,没有其他单词出现两次 下面是我能得到的最

我目前正在学习Python,并试图解决一个免费的教程问题

问题是

一位作家正在写他们的新诗《图灵与机器》。他们雇佣你来确定出现次数最多的单词。您可以通过反复调用input()来访问这首诗的行,最后一行包含三个字符###。所有行由单个空格分隔的单词组成;没有数字或标点符号。将所有单词转换为小写,并打印出现次数最多的单词(我们保证不会出现平局)。 例如,如果输入是

这是一条像起泡酒一样的线

快排好队,否则就排在最后

###

那么输出应该是

线

因为它出现两次,没有其他单词出现两次

下面是我能得到的最接近解决方案的东西

除其他外,它还缺少允许用户重复调用input()的功能

它只打印出最常用单词的最大数量,而不是问题想要的单词本身


这首诗由shell网站提供,网址为

假设用户一次只输入一行诗

请帮忙。非常感谢

def poem(P):

      P_lower = P.lower()

      P_split = P_lower.split()

      word_list = []

      wordfreq = []

      for i in P_split:
            word_list.append(i)

      for i in P_split:
            wordfreq.append(P_split.count(i))

      print(max(wordfreq))


poem('Here is a line like line sparkling line wine')

这不使用任何“受限”工具,只使用lower()、split()和sort()返回出现次数最多的单词

def  main():
    done = False
    P = ""
    while not done:
        new_line = input()
        if new_line != "###":
            P += new_line + " "
        else:
            done = True
    poem_words = P.lower().split()
    poem_words.sort()

    # Initialize variables
    temp = ""
    max_count = 0
    icount = 1
    max_word = ""

    # Do the loop
    for i in range(len(poem_words)):
        if temp == poem_words[i]:
            icount += 1
        else:
            temp = poem_words[i]
            icount = 1
        if icount > max_count:
            max_count = icount
            max_word = temp
    print(max_word)
    return

if __name__ == "__main__":
    main()

顺便说一句,对于那些对koukouviou之前的伟大答案感兴趣的人来说,这是一个在Python 3 shell中工作的答案:

def words(P):
    poem_words = P.lower().split()
    poem_words.sort()

    # Remove the # signs
    poem_words = [x for x in poem_words if (x != '#' and x != '###')]

    # Initialize variables
    temp = ""
    max_count = 0
    icount = 1
    max_word = ""

    # Do the loop
    for i in range(len(poem_words)):
        if temp == poem_words[i]:
            icount += 1
        else:
            temp = poem_words[i]
            icount = 1
        if icount > max_count:
            max_count = icount
            max_word = temp
    return max_word


poem = "Here is a line like sparkling wine\nLine up fast or be the last\n# # #"
print(words(poem))

这是我的方法。我的代码包含两个或多个单词具有相同数字的可能性 关于外表

    def reading():
        global ListLine                 # We make variable 'ListLine' global in case if function CountWord() does not take it
        ListLine = []                   # We define an empty list 'ListLine'
        while True:
            Line = input()              # A line of poem is entered
            NewLine = Line.split()      # We make a list 'NewLine' of individual words

            for i in range(0, len(NewLine)):
                NewString = NewLine[i].lower()    # For each word in list 'NewLine' we make it lowercase
                NewLine.insert(i, NewString)      # We add to a list a lowercase version of a individual word value at position i
                del NewLine[i + 1]                # We delete original word at position i + 1

            ListLine = ListLine + NewLine

            if ListLine[len(ListLine) - 1] == "###":  # If line ends with '###', the loop ends
                break
        return ListLine                           # We get a list of individual words


    def CountWord(ListLine):
        CountList = []                          # We define an empty list 'CountList'
        for i in range(0, len(ListLine)):
            CountWord = ListLine.count(ListLine[i])  # Counting how many times an individual word appears in 'ListLine'
            CountList.insert(i, CountWord)           # We add to a list the result of frequency of appearance of an individual word at position i

        return CountList       # We get a list of counts of individual words


    def Word(CountList):
        global WordList   # We make variable 'WordList' global in case if function RemoveDuplicate() does not take it
        WordList = []     # We defined an empty list 'WordList'
        for i in range(0, len(CountList)):
            if CountList[i] == max(CountList):  # For each index in 'CountList' that has a value of highest count of appearance of individual word,
                Word = ListLine[i]              # get a word from 'ListLine' which have the same index
                WordList.insert(i, Word)        # Add to a list a word at position i a.k.a index
            elif CountList[i] != max(ListLine):  # If above condition was not met, we skip a step
                continue

        return WordList     # We get a list of individual words that appears the most in 'NewLine', but might contains duplicates.


    def RemoveDuplicate(Wordlist):
        ResultList = []   # We define an empty list 'CountList'
        for i in WordList:
            if i not in ResultList:  # To remove duplicates we define a condtiotion; if a list 'ResulList' does not contain
                                     # an individual word we insert in a list.
                ResultList.append(i)

        String = ' '.join(ResultList)  # We convert a list into a string

        if String.endswith('###'):     # If string ends with '###', we remove last four characters (space included),
                                       # else return just final result
            return String[:-4]
        else:
            return String


    print(RemoveDuplicate(Word(CountWord(reading())))) # Print the output

我正在学习相同的教程,并给出了下面的代码示例。这不是很好的代码,但符合教程的限制,并对每个步骤进行了注释。此不会通过源页面上的测试仪

#create 4 lists
newList=[]    #to intake each line of new text
fulList=[]    #combine all text in one long list
uniqueList=[] #list of unique words
wordFreq=[]   #frequency of those unique words

#take in all lines
while True:
   newLine=input()
   if newLine=="###":
      break
   newList=newLine.lower().split() #convert all words to lowercase
   fulList=fulList+newList         #add this to the fulList of all words

#clear memory of items we no longer need
newList=[]
newLine=[]

#find and store all unique words
for i in range(0,len(fulList)): #scan all of fulList
   checkWord = fulList[i]
   if checkWord in uniqueList:  #if we already have that word, skip it
      continue
   uniqueList.append(checkWord) #otherwise add it to the uniqueList

#create a blank freq table of same length as uniqueList
#technically this was created on line 5, but now you understand the context
#note the use of len(uniqueList) so both lists are the same length
wordFreq=[0]*(len(uniqueList))

#now iterate through each word in your uniqueList using range i
#checking for every word in the fullList which we will iterate using range j
for i in range(0,len(uniqueList)):
   for j in range(0,len(fulList)):
      if uniqueList[i]==fulList[j]:
         wordFreq[i] = wordFreq[i]+1 #increase the count for that item

#create a variable for most common word, this is the largest number in wordFreq
maxWord = max(wordFreq)

#iterate through wordFreq to find that value
for i in range(0,len(wordFreq)):
   if wordFreq[i]==maxWord:
      print(uniqueList[i]) #print that word from uniqueList

我的解决方案比上面更简单

poem=''
while True:
    poem=poem+' '+(input())  
    if poem.endswith('###'): break  

poem=poem.lower()  
listOFstring=poem.split()  

l=[]  
for i in listOFstring:  
    l.append(listOFstring.count(i))  

print(listOFstring[l.index(max(l))])  

这首诗在档案中吗?这首诗由位于koukouviou的shell网站提供,非常感谢您的努力。它看起来比我能想到的要好得多。但不幸的是,它在编码练习中失败了:诗意的分析可能是因为我们还没有在那个网站上学习lambda。我也不能让它在Python3 shell中工作。如果可以的话,我会投你一票。再次感谢你的努力。koukouviou,非常感谢你的努力。它看起来比我能想到的要好得多。但不幸的是,它在编码练习中失败了:诗意的分析可能是因为我们还没有在那个网站上学习lambda。我也不能让它在Python3 shell中工作。如果可以的话,我会投你一票。再次感谢您的努力。我编辑了回复以更正此问题。如果答案有效,请随意接受,但它仍然无法通过shell at I wounder,如果您可以在“编码练习:诗意分析”部分修改您的程序以通过该网站的shell测试?尽管如此,对于Python3 shell,我还是会接受您的答案。非常感谢,非常感谢koukouviou。它起作用了。我只需要修改你的程序,并给一个缩进返回,它的工作。你真聪明。
poem=''
while True:
    poem=poem+' '+(input())  
    if poem.endswith('###'): break  

poem=poem.lower()  
listOFstring=poem.split()  

l=[]  
for i in listOFstring:  
    l.append(listOFstring.count(i))  

print(listOFstring[l.index(max(l))])