簡體   English   中英

如何使用def功能

[英]how to use the def function

我是python的新手,所以我希望你們能幫助我。 目前,我正在使用import函數獲取我的輸出,但是我希望將def函數包括在這組計算出前10個最常用單詞的代碼中。 但我不知道。 希望你們能幫助我。 提前致謝!!!

import collections
import re
file = open('partA', 'r')
file = file.read()
stopwords = set(line.strip() for line in open('stopwords.txt'))
stopwords = stopwords.union(set(['it', 'is']))
wordcount = collections.defaultdict(int)
"""
the next paragraph does all the counting and is the main point of difference from the original article. More on this is explained later.
"""
pattern = r"\W"
for word in file.lower().split():
    word = re.sub(pattern, '', word)
    if word not in stopwords:
        wordcount[word] += 1

to_print = int(input("How many top words do you wish to print?"))
print(f"The most common {to_print} words are:")

mc = sorted(wordcount.items(), key=lambda k_v: k_v[1], reverse=True) [:to_print]
for word, count in mc:
    print(word, ":", count)

輸出:您希望打印多少個最重要的單詞?30最常見的30個單詞是:嘿:1那里:1這個:1 joey:1方式:1前進:1

'def'用於創建用戶定義的函數,以便以后在腳本中調用。 例如:

def printme(str):
    print(str)


printme('Hello')

現在,我創建了一個名為“ printme”的函數,稍后將其調用以打印字符串。 這顯然是毫無意義的功能,因為它只執行“打印”功能,但是我希望這可以弄清“ def”的目的!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM