?本關(guān)任務(wù):編寫一個能統(tǒng)計文件中單詞數(shù)量的小程序,用replace替換文本內(nèi)的標(biāo)點
代碼如下:
# 補充你的代碼
a = input()
import string
with open(f'/data/bigfiles/{a}', 'r', encoding='utf-8') as text: # 打開文件a.txt,創(chuàng)建文件對象
txt = text.read() # 讀文件為字符串
for i in ",.!\'":
txt = txt.replace(i, " ")
x1 = txt.split()
print('共有'+str(len(x1))+"個單詞")
( 整體思路,先將文本中的標(biāo)點符號用空格替換,然后用空格分隔單詞,最后用len()
統(tǒng)計文本中單詞的數(shù)量 )
相關(guān)知識
為了完成本關(guān)任務(wù),你需要掌握:
1.獲取文件內(nèi)容 2.字符串方法的使用
1.讀取文件
open(filename)
函數(shù)可以打開諸如txt
,csv
等格式的文件。????????????????????????????????????????????????????????????????
例如:
with open('a.txt', 'r', encoding='utf-8') as text: # 打開文件a.txt,創(chuàng)建文件對象
txt = text.read() # 讀文件為字符串
print(txt) # 輸出字符串
2.字符串方法
為了方便編程,Python
為我們提供了許多方法這里我們將學(xué)習(xí)其中的兩個字符串方法。
2.1替換
str.replace(oldvalue, newvalue, count)
方法是在字符串str中,用另一個newvalue字符串替換oldvalue字符串count次。
參數(shù)值:文章來源地址http://www.zghlxwxcb.cn/news/detail-483351.html
序號 | 參數(shù) | 描述 |
---|---|---|
1 | oldvalue | 必需。要檢索的字符串。 |
2 | newvalue | 必需。替換舊值的字符串。 |
3 | count | 可選。數(shù)字,指定要替換的舊值出現(xiàn)次數(shù)。默認(rèn)為替換所有出現(xiàn)的檢索字符串。 |
示例如下:
txt = "I like bananas. She likes bananas too. "
x1 = txt.replace("bananas", "apples") # 替換所有
print(x1) # I like apples. She likes apples too.
x2 = txt.replace("bananas", "apples", 1) # 只替換一次
print(x2) # I like apples. She likes bananas too.
2.2切分
str.split(sep=None, maxsplit=- 1)
將字符串拆分成一個列表,其中每個單詞都是一個列表項。可以指定分隔符,默認(rèn)分隔符是空白字符(包括空格、制表\t、換行\(zhòng)n、回車\r、進紙\f和縱向制表符\v)。文章來源:http://www.zghlxwxcb.cn/news/detail-483351.html
參數(shù)值:
序號 | 參數(shù) | 描述 |
---|---|---|
1 | sep | 可選。規(guī)定分割字符串時要使用的分隔符。默認(rèn)值為空白字符。 |
2 | maxsplit | 可選。規(guī)定要執(zhí)行的拆分?jǐn)?shù)。默認(rèn)值為 -1,即“所有出現(xiàn)次數(shù)”。 |
到了這里,關(guān)于5.1統(tǒng)計英文文件中的單詞數(shù)python的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!