输入一个字符串,字符串包含多个单词,单词间用一个空格分隔,字符串里没有任何标点符号。要求将该字符串中单词和单词出现的次数保存到字典中,并输出字典。
时间: 2023-08-07 12:40:40 浏览: 48
好的,可以使用 Python 语言来实现这个功能。可以按照以下步骤进行:
1. 输入字符串;
2. 将字符串按照空格分割成单词列表;
3. 遍历单词列表,统计每个单词出现的次数,并将单词和次数保存到字典中;
4. 输出字典。
下面是 Python 代码示例:
```python
# 输入字符串
string = input('请输入字符串:')
# 将字符串按照空格分割成单词列表
word_list = string.split()
# 统计每个单词出现的次数,并将单词和次数保存到字典中
word_dict = {}
for word in word_list:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
# 输出字典
print(word_dict)
```
测试示例:
输入:`This is a sample text for word frequency analysis`
输出:`{'This': 1, 'is': 1, 'a': 1, 'sample': 1, 'text': 1, 'for': 1, 'word': 1, 'frequency': 1, 'analysis': 1}`
相关问题
字符串切分连接:输入一个包含多个单词的英文句子,单词间以空格分隔,标点符号后跟一个空格。定义一个函数,功能是用指定的符号把单词连接起来。
好的,我理解了你的问题,可以给你一个 Python 实现的例子:
```python
def join_words(sentence, symbol):
words = sentence.split()
for i in range(len(words)):
# 去除标点符号
words[i] = words[i].strip('.,!?')
return symbol.join(words)
```
这个函数接收两个参数,第一个是输入的句子,第二个是指定的符号。它首先将句子按照空格切分成单词,然后对每个单词去除标点符号,最后使用指定的符号将单词连接起来。你可以这样调用这个函数:
```python
sentence = "This is a test sentence, with some punctuation."
symbol = "-"
result = join_words(sentence, symbol)
print(result)
```
输出结果为:
```
This-is-a-test-sentence-with-some-punctuation
```
注意,这个例子中使用了 Python 内置的字符串方法 `split` 和 `join`,以及字符串的 `strip` 方法来去除标点符号。如果你使用其他编程语言,需要使用相应的方法来实现这些功能。
任意输入一个字符串,把里面的标点符号全换成空格
好的,以下是代码:
```python
import string
def replace_punctuation_with_space(s):
return s.translate(str.maketrans(string.punctuation, ' ' * len(string.punctuation)))
input_str = input("请输入一个字符串:")
output_str = replace_punctuation_with_space(input_str)
print(output_str)
```
这个函数会将输入字符串中的所有标点符号都替换成空格,并返回替换后的字符串。