date.txt中保存有若干个单词,每个单词一行。请编写一个程序从文件中将所有单词读出,找到其中最长的单词,然后将其保存到result.txt中,程序需保存test.py中。注意:重复出现了单词算不同的单词
时间: 2024-05-05 14:22:35 浏览: 30
以下是一个Python程序,可以从date.txt中读取单词,找到其中最长的单词并将其保存到result.txt中。
```python
# -*- coding: utf-8 -*-
import os
def find_longest_word(file_path):
max_len = 0
longest_word = ''
with open(file_path, 'r') as f:
for line in f:
word = line.strip()
if len(word) > max_len:
max_len = len(word)
longest_word = word
return longest_word
if __name__ == '__main__':
file_path = 'date.txt'
longest_word = find_longest_word(file_path)
with open('result.txt', 'w') as f:
f.write(longest_word)
print(f'The longest word is {longest_word} and saved in result.txt.')
```
你可以将以上代码保存为test.py,然后在终端中执行`python test.py`即可得到结果。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)