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

2024-10-01 07:46:59 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的示例是去除标点符号并将文本从冉波.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

现在,在这个拆分之后,我怎么能找到这个列表中有多少个单词?在

^{pr2}$

Tags: 文件文本txt示例readspaceopenlower
1条回答
网友
1楼 · 发布于 2024-10-01 07:46:59
white_space_words = lowercased.split()

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

^{pr2}$

退货

^{3}$

但你也可以换一种方式:

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)

相关问题 更多 >