1. 程式人生 > >.第二次作業(Python)

.第二次作業(Python)

能力 文件 yun spa 鍛煉 str strong txt 功能需求

Gitee代碼鏈接https://gitee.com/dsjyun/WordCount/tree/master

一, 功能需求

wc.exe -c file.c //返回文件 file.c 的字符數

wc.exe -w file.c //返回文件 file.c 的單詞總數

wc.exe -l file.c //返回文件 file.c 的總行數

wc.exe -o outputFile.txt file.c //將結果輸出到指定文件outputFile.txt

二,解題思路:

(1)這次作業並不難,所以我選用了正在自學的Python來實現WordCount。

(2)運用正則表達式提取.c文件中所有的字符;

(3)以空格為分隔符號提取.c文件中所有的單詞數;

(4)運用Python中ReadLines方法提取.c文件中所有的行數。

三,主要代碼

1.統計字符數

if dir_path.find("-c")!=-1:

    txt = dir_path.split(" ")[-1].split(".")[0]
    z =".txt"
    path = os.getcwd()+"\\"+txt+".c"
    w = open(path,"a+")                 //打開用戶需要解析的.c文件
    z = w.read()
    r = re.compile(r
(.|\n)*) //正則表達式規則,用來統計字符個數 w.close() path_new = os.getcwd()+"\\"+"result.txt" result = open(path_new,"a+") result.write(txt+".c"+","+"字符數:"+str(len(r.search(z).group()))) result.close()

2.統計行數;

if dir_path.find("-w")!=-1:
    txt = dir_path.split(" ")[-1].split("."
)[0] z =".txt" path = os.getcwd()+"\\"+txt+".c" w = open(path,"a+") z = w.read() print len(z.split(" ")) w.close() path_new = os.getcwd()+"\\"+"result.txt" result = open(path_new,"a+") result.write(txt+".c"+","+"單詞數:"+str(len(z.split(" ")))) result.close()

3.統計行數;

if dir_path.find("-l")!= -1:
    txt = dir_path.split(" ")[-1].split(".")[0]
    z =".txt"
    path = os.getcwd()+"\\"+txt+".c"
    jii = open(path,rU)
    count = len(jii.readlines())
    path_new = os.getcwd()+"\\"+"result.txt"
    jii.close()
    result = open(path_new,"a+")
    result.write(txt+".c"+","+"行數:"+str(count))
    result.close()
    print count

四,功能測試

技術分享圖片技術分享圖片

五,總結

這次作業很有意義,首先作業嚴格貼合我們學習的內容,使我們對理論知識的實踐;並且老師也要求我們自己編碼實現WordCount,也可以鍛煉我們的編程能力。

.第二次作業(Python)