[英]Remove unwanted '[' and ']' in final output
您好,我正在編寫一個函數,該函數接受其中包含文本的文件並返回文件中最常見的單詞。 我當前的代碼如下所示:
import collections
def approximate_song(filename):
text = open(filename).read()
counts = collections.Counter(text.lower().split())
return [elem for elem, _ in sorted(counts.most_common(), key=lambda
x: (-x[1], x[0]))[:1]]
這將返回最常見的單詞。 但是,當它應以“此處的單詞”形式返回時,它以['word here']的格式返回它。 (不在方括號中,而僅在括號中)。
任何幫助將非常感激!
在Python中,列表用[]
表示。 例如, [1,2,3,4,5]
是一個列表。 為了訪問單個元素,我們使用索引。 因此,如果a = [1,2,3,4,5]
是一個列表,則可以通過a[0]
訪問第一個元素,通過a[1]
訪問第二個元素,依此類推。
您的代碼返回整個列表,而不是元素。 對列表的返回[0]
元素的簡單修改即可實現您的目標。
import collections
def approximate_song(filename):
text = open(filename).read()
counts = collections.Counter(text.lower().split())
return [elem for elem, _ in sorted(counts.most_common(), key=lambda
x: (-x[1], x[0]))[:1]][0]
print(approximate_song('README.txt'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.