我想问一下大家,怎么把这个Python程序改成能处理多个重复词,感谢!
import re
s = "This is a a desk is desk."
words = re.findall(r'\b\w+\b', s) # 使用正则表达式提取单词
unique_words = list(set(words)) # 使用集合去重
result = ' '.join(unique_words) # 将去重后的单词列表转换为字符串
print(result)
# 结果: is desk a This
一种思路是改正则表达式
但是如果一句话里有多个不同的单词重复,怎么都没办法
所以你不如写个while,循环执行,一直到正则匹配不到重复单词,就break
其他python学习笔记集合:
Python基础知识详解(十)小结,用python实现教师信息管理系统
上篇用python实现教师信息管理系统,这里学几个实现这个系统过程中遇到的问题
针对问题:如何在Python中处理多个重复词?
可以使用Python中的set去除重复词。如果数据是以字符串的形式存储,可以先进行分词,然后再使用set函数去除重复词。
示例代码:
data = "hello world hello python world"
words = data.split()
unique_words = set(words)
print(unique_words)
输出结果为:
{'hello', 'python', 'world'}
如果需要统计词频,可以使用Python中的collections模块中的Counter函数。
示例代码:
from collections import Counter
data = "hello world hello python world"
words = data.split()
word_count = Counter(words)
print(word_count)
输出结果为:
Counter({'hello': 2, 'world': 2, 'python': 1})