python统计句子中单词个数并输出最长单词
时间: 2023-05-12 22:02:39 浏览: 153
可以使用以下代码实现:
```python
sentence = input("请输入句子:")
words = sentence.split()
print("单词个数为:", len(words))
longest_word = max(words, key=len)
print("最长的单词是:", longest_word)
```
输入一个句子后,程序会输出该句子中单词的个数以及最长的单词。
相关问题
python统计单词个数并输出最长单词
可以使用Python的collections模块中的Counter函数来统计单词个数,然后使用max函数找到最长的单词。以下是示例代码:
```python
from collections import Counter
text = "This is a sample text with some words. This is another sentence with more words."
# 统计单词个数
word_counts = Counter(text.split())
# 输出单词个数
print("单词个数:", sum(word_counts.values()))
# 输出最长单词
longest_word = max(word_counts, key=len)
print("最长单词:", longest_word)
```
输出结果为:
```
单词个数: 15
最长单词: sentence
```
python输出句子中最长英语单词
可以使用split()函数将句子分割成单词,然后使用max()函数找到最长的英语单词。以下是示例代码:
sentence = "This is a sample sentence with some long English words."
words = sentence.split()
longest_word = max(words, key=len)
print("The longest English word in the sentence is:", longest_word)
输出结果为:
The longest English word in the sentence is: English
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)