我正在嘗試創建一個函式,其中將檔案名作為引數,并且該函式回傳檔案中最長的單詞,并在其前面附加行號。這是我到目前為止所擁有的,但它沒有產生我需要的預期輸出。
def word_finder(file_name):
with open(file_name) as f:
lines = f.readlines()
line_num = 0
longest_word = None
for line in lines:
line = line.strip()
if len(line) == 0:
return None
else:
line_num = 1
tokens = line.split()
for token in tokens:
if longest_word is None or len(token) > len(longest_word):
longest_word = token
return (str(line_num) ": " str(longest_word))
uj5u.com熱心網友回復:
我認為這是找到單詞的最短方法,如果不是,請正確
def wordFinder(filename):
with open(filename, "r") as f:
words = f.read().split() # split() returns a list with the words in the file
longestWord = max(words, key = len) # key = len returns the word size
print(longestWord) # prints the longest word
uj5u.com熱心網友回復:
問題
究竟是什么ewong 診斷的:
最后一個
return陳述句縮進太深
目前:
- 僅第一行中最長的單詞
解決方案
應該與回圈的列對齊,在回圈之后執行。
def word_finder(file_name):
with open(file_name) as f:
lines = f.readlines()
line_num = 0
longest_word = None
for line in lines:
line = line.strip()
if len(line) == 0:
return None
else:
line_num = 1
tokens = line.split()
for token in tokens:
if longest_word is None or len(token) > len(longest_word):
longest_word = token
# return here would exit the loop too early after 1st line
# loop ended
return (str(line_num) ": " str(longest_word))
然后:
- 檔案中最長的單詞,其前面附有行號。
改進
def word_finder(file_name):
with open(file_name) as f:
line_word_longest = None # global max: tuple of (line-index, longest_word)
for i, line in enumerate(f): # line-index and line-content
line = line.strip()
if len(line) > 0: # split words only if line present
max_token = max(token for token in line.split(), key = len) # generator then max of tokens by length
if line_word_longest is None or len(max_token) > len(line_word_longest[1]):
line_word_longest = (i, max_token)
# loop ended
if line_word_longest is None:
return "No longest word found!"
return f"{line_word_longest[0]}: '{line_word_longest[1]}' ({len(line_word_longest[1])} chars)"
也可以看看:
- 帶有列舉的基本 python 檔案-io 變數
- Python 中的 List Comprehensions 計算串列的最小值和最大值
針對類似問題的一些 SO 研究:
- 來自所有語言的靈感:
longest word in file - 只有蟒蛇:
[python] longest word in file - 非蟒蛇:
-[python] longest word in file
uj5u.com熱心網友回復:
減少這個有點樂趣:
def word_finder(file_name):
with open("test.c") as f:
lines = [{ 'num': i,
'words': (ws := line.split()),
'max': max(ws, key=len) if ws else '',
'line': line }
for i, line in enumerate(f.readlines())]
m = max(lines, key=lambda l: len(l['max']))
return f"{m['num']}: '{m['max']}'"
我們使用串列推導將每一行變成一個字典,描述其行號、包含它的所有單詞、最長單詞和原始行。在計算最長單詞時,如果為空,我們只需插入一個空字串,從而避免處理空序列ws時出現例外。max
然后可以直接使用max找到最長單詞的行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/484155.html
標籤:Python
上一篇:撰寫一個程式,從用戶那里讀取正數并在用戶輸入負數時停止
下一篇:拆分串列中的字串
