簡體   English   中英

接受文件並將參數從命令行傳遞給函數沒有輸出

[英]Accept file and pass arguments to function from command line gives no output

我正在編寫一個腳本來接受(可選)命令行中的兩個參數:--top 返回按計數排名前列的單詞,例如 --top 5,返回前 5 個; --lower 在計算唯一值之前降低單詞列表。

我到了這個階段,但沒有得到任何輸出:

import collections
import argparse

def counts(text, top = 10, case = None):
    """ returns counts. Default is top 10 frequent words without change of case"""
    # split on whitespace
    word_list = text.split()

    if case is None:
        c = collections.Counter(word_list)
        return c.most_common(top)
    else:
        c = collections.Counter([w.lower() for w in word_list])
        return c.most_common(top)

# declare parser
parser = argparse.ArgumentParser()

# add argument --top
parser.add_argument("--top", help="returns top N words. If not specified it returns top 10", type=int)

# add argument --lower
parser.add_argument("--lower", help = "lowercase all the words.('StackOverFlow' and 'stackoverflow' are counted equally.")

# add argument filename
parser.add_argument("filename", help = "accepts txt file")

args = parser.parse_args()

# read text file
file = open(args.filename, 'r').read()

counts(text = file, top = args.top, case = args.lower)

當我運行腳本時

$python script.py text.txt --top 5 --lower

我沒有輸出。 任何線索我哪里出錯了?

如果文件要輸出一些東西,我會期望:

(word1 count1)
(word2 count2)
(word3 count3)
(word4 count4)
(word5 count5)

基於上面驚人的評論,工作代碼是:

import collections
import argparse

def counts(text, top = 10, case = False):
    """ returns counts. Default is top 10 frequent words without change of case"""
    # split on whitespace
    word_list = text.split()

    if case is False:
        c = collections.Counter(word_list)
        return c.most_common(top)
    else:
        c = collections.Counter([w.lower() for w in word_list])
        return c.most_common(top)

# declare parser
parser = argparse.ArgumentParser()

# add argument --top
parser.add_argument("--top", help="returns top N words. If not specified it returns top 10", type=int)

# add argument --lower
parser.add_argument("--lower", help = "lowercase all the words.('StackOverFlow' and 'stackoverflow' are counted equally.",action='store_true')

# add argument filename
parser.add_argument("filename", help = "accepts txt file")

args = parser.parse_args()

# read text file
file = open(args.filename, 'r').read()

if args.top:
    print(counts(text = file, top = args.top, case = args.lower))
else:
    print(counts(text = file, case = args.lower))

暫無
暫無

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

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