用空格分割字符串,然后进行计数

时间:2015-02-11 14:26:52

标签: python string split whitespace

下面的示例是从ranbo.txt文件中剥离标点并将文本转换为小写...

帮我用空格分割它

infile = open('ranbo.txt', 'r')
lowercased = infile.read().lower() 
for c in string.punctuation:
    lowercased = lowercased.replace(c,"")
white_space_words = lowercased.split(?????????)
print white_space_words

现在,在此分割后 - 我怎样才能找到这个列表中有多少个单词?

count or len function?   

1 个答案:

答案 0 :(得分:1)

white_space_words = lowercased.split()

使用任意长度的空白字符进行拆分。

'a b \t cd\n  ef'.split()

返回

['a', 'b', 'cd', 'ef']

但你也可以这样做:

import re
words = re.findall(r'\w+', text)

返回text所有“字词”的列表。

使用len()获取其长度:

len(words)

如果你想将它们加入到带换行符的新字符串中:

text = '\n'.join(words)

整体而言:

with open('ranbo.txt', 'r') as f:
    lowercased = f.read().lower() 
words = re.findall(r'\w+', lowercased)
number_of_words = len(words)
text = '\n'.join(words)