Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

python统计文本中的单词数目 #18

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions pythonProject/统计文本中的单词数目.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import re


def count_words(text):
# 使用正则表达式移除文本中的标点符号,并转换为小写,然后分割成单词列表
words = re.findall(r'\b\w+\b', text.lower())
return len(words)


# 示例文本
sample_text = "Hello, this is a sample text to demonstrate word counting in Python. It includes punctuation!"

# 调用函数并打印结果
word_count = count_words(sample_text)
print(f"The number of words in the sample text, excluding punctuation, is: {word_count}")