python编写程序,给定若干个字符串,通过函数来统计这若干个字符串中包含多少个不同的单词。
时间: 2024-03-21 10:44:12 浏览: 11
可以使用以下代码来实现:
```python
import re
def count_unique_words(*strings):
words = set()
for string in strings:
# 利用正则表达式提取字符串中的单词
pattern = r'\b\w+\b'
matches = re.findall(pattern, string)
# 将单词加入集合中
words.update(matches)
return len(words)
```
其中,`count_unique_words` 函数接收若干个字符串参数,使用正则表达式从字符串中提取单词,并将所有不同的单词存入一个集合中,最后返回集合的长度,即不同单词的数量。
使用方法:
```python
strings = [
'hello world',
'hello python',
'python is awesome',
'hello world'
]
count = count_unique_words(*strings)
print(count) # 4
```
在这个例子中,输入的字符串列表中一共包含 4 个不同的单词:`hello`、`world`、`python` 和 `is`。
相关问题
PYthon编写程序,给定若干个字符串,通过函数来统计这若干个字符串中包含多少个不同的单词。
可以使用Python中的set数据结构来实现单词去重,再统计set中元素个数即可。
以下是一个示例代码:
```python
def count_words(*strings):
words = set()
for string in strings:
words.update(string.split())
return len(words)
strings = ["this is a test", "hello world", "test test"]
count = count_words(*strings)
print(count) # 输出:5
```
在这个示例代码中,函数`count_words`接收若干个字符串参数,使用set数据结构统计这些字符串中包含多少个不同的单词。在循环遍历每个字符串时,使用字符串的`split`方法将字符串按照空格分割成单词,并将这些单词加入到set中。最后,返回set中元素的个数即为不同的单词个数。
python编写一个函数,给定一个字符串,判断该字符串是否为回文
一个回文字符串是指正着读和倒着读都是一样的字符串,比如 "racecar"。可以使用以下代码实现:
```python
def is_palindrome(string):
# 判断字符串是否为回文
return string == string[::-1]
```
这里使用了 Python 中的字符串切片语法,`string[::-1]` 表示将字符串反转。如果反转后的字符串和原字符串相同,那么就是回文字符串,返回 `True`;否则返回 `False`。