簡體   English   中英

Python 從文件中提取最長的單詞

[英]Python Pulling the longest word from a file

希望每個人都做得很好。 我需要在 Python 中編寫一個程序,該程序讀取 a.txt 文件並找到最長的單詞。 這很簡單,但有一些限制。

您不能以任何方式使用輸入 function、拆分 function 或列表。

我整天都在為此苦苦掙扎。 任何人有任何想法或至少可以指出我正確的方向?

您可以使用re模塊作為使用split function 的替代方法:

import re

def longest_word(file_name="try.txt"):
    longest_word = ""
    with open(file_name, 'r') as file:
         for line in file.readlines():
             for word in re.findall(r'\S+', line):
                 if len(word ) > len(longest_word):
                     longest_word = word
    return longest_word, len(longest_word)

word, length = longest_word("test.txt")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM