在Python中,创建一个长英文字符串,给出字符串中的单词(应删除标点符号),计算单词总数量 -提示:用列表推导
时间: 2024-06-12 10:06:24 浏览: 82
以下是一个示例:
```python
text = "Python is a high-level programming language, with applications in numerous areas, including web programming, scripting, scientific computing, and artificial intelligence. It is very popular and used by organizations such as Google, NASA, and CERN. Python's design philosophy emphasizes code readability and ease of use, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java."
# 将标点符号替换为空格,然后按空格分割字符串,得到单词列表
words = text.replace(",", "").replace(".", "").replace("'", "").split()
# 使用列表推导计算单词总数
word_count = len([word for word in words])
print("单词总数为:", word_count)
```
输出结果为:
```
单词总数为: 63
```
相关问题
用Python创建一个长英文字符串,给出字符串中的单词(应删除标点符号)组成的列表,计算单词总数量
可以使用以下代码创建长英文字符串,给出单词列表并计算单词总数量:
```python
import string
# 创建长英文字符串
long_string = """In the beginning God created the heavens and the earth. Now the earth was formless and empty, darkness was over the surface of the deep, and the Spirit of God was hovering over the waters."""
# 删除标点符号
translator = str.maketrans('', '', string.punctuation)
long_string = long_string.translate(translator)
# 给出单词列表
word_list = long_string.split()
# 计算单词总数量
word_count = len(word_list)
print(word_list)
print(word_count)
```
输出为:
```
['In', 'the', 'beginning', 'God', 'created', 'the', 'heavens', 'and', 'the', 'earth', 'Now', 'the', 'earth', 'was', 'formless', 'and', 'empty', 'darkness', 'was', 'over', 'the', 'surface', 'of', 'the', 'deep', 'and', 'the', 'Spirit', 'of', 'God', 'was', 'hovering', 'over', 'the', 'waters']
35
```
python编写程序实现:输入一个字符串,字符串包含多个单词,单词间用一个空格分隔,字符串里没有任何标点符号。要求将该字符串中单词和单词出现的次数保存到字典中,并输出字典。 输入格式: 一个包含多个单词的字符串,单词间用一个空格分隔,字符串里没有任何标点符号。 输出格式: 输出一个字典。
好的,下面是代码实现,将其复制粘贴到Python环境中即可:
```python
s = input() # 输入一个字符串
words = s.split() # 将字符串按照空格分隔成单词列表
word_dict = {} # 定义一个空的字典,用于存储单词和出现次数
# 遍历每个单词
for word in words:
if word not in word_dict:
# 如果单词第一次出现,则将其加入字典,并将出现次数设为1
word_dict[word] = 1
else:
# 如果单词不是第一次出现,则将其出现次数加1
word_dict[word] += 1
print(word_dict) # 输出字典
```
运行程序后,输入一个字符串,程序就会输出该字符串中每个单词的出现次数。例如,如果输入字符串`hello world hello python world python python`,则输出的字典为`{'hello': 2, 'world': 2, 'python': 3}`。
阅读全文