簡體   English   中英

Python-編寫一個函數以打開.txt文件並返回其中的單詞總數

[英]Python- Write a function that opens a .txt file and returns the total number of words in it

一直嘗試這樣做,但是由於某種原因,我無法理解這個簡單的代碼。 不必擔心標點符號,它只是純文本。 目前我所擁有的是:

def wc(filename):

    f = open(filename, 'r')    # Read
    words = f.readlines()
    f.close()
    print int(filename.split())
    p = 1
    for word in words:
        p += words
    return p

一直在尋找答案,但只能找到其中包含特定字詞的示例。

f = open(filename)    # Read
words = f.read()
f.close()
words = words.split()
print len(words)

split可以使用參數sep ,該參數指定要分割的字符(分隔符)。

字符串模塊具有一些常量,包括punctuationwhitespace

把它們放在一起你會得到

import string

filename = 'words.txt'

with open(filename) as f:
    words = f.read().split(string.whitespace + string.punctuation)

print len(words)

這給你線

words = f.readlines()

您需要通過.split()方法在其中拆分word變量。

word_count += len(word.split())
with open(filename, 'r+') as f:
    words = f.read()
words = words.split(' ')
words_nbr = len(words)
print(words_nbr)

暫無
暫無

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

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