简体   繁体   English

Python-编写一个函数以打开.txt文件并返回其中的单词总数

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

Been trying to do this for a while but for some reason i cant get my head around this simple code. 一直尝试这样做,但是由于某种原因,我无法理解这个简单的代码。 Dont need to worry about punctuation, its just plain text. 不必担心标点符号,它只是纯文本。 At the moment all i have is: 目前我所拥有的是:

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

been looking for an answer for a while but can only find examples where they count specific words. 一直在寻找答案,但只能找到其中包含特定字词的示例。

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

split can take a parameter sep which specifies what characters to split on (the separator). split可以使用参数sep ,该参数指定要分割的字符(分隔符)。

The string module has some constants including punctuation and whitespace . 字符串模块具有一些常量,包括punctuationwhitespace

Putting them together you get 把它们放在一起你会得到

import string

filename = 'words.txt'

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

print len(words)

This one gives you lines 这给你线

words = f.readlines()

You need to split word variable inside for via .split() method. 您需要通过.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