[英]Count the amount of lists in a list (nested list) for each length Python
[英]Create a list of lists in python with length and count for words
我有一個家庭作業,我必須定義一個函數,該函數要求用戶輸入一個段落並創建一個列表列表(例如 [[x,y],[x1,y2],[x3,y3]),其中 x = 指定的字符串中單詞的長度,y = 指定長度的單詞數。 (例如 [[1,2], [2,3], [4,4], [6,1]]... 1 是 1 個字母的單詞,2 是 1 個字母的單詞的計數,依此類推向前。)
這是我目前所擁有的:
def wordCount():
words = []
wordCount_text_length = []
word_count = []
text = input('Please enter a paragaph of regular English text: \n')
words = (text.split())
for x in words:
wordCount_text_length.append(len(x))
for y in wordCount_text_length:
word_count.append(wordCount_text_length.count(y))
當我在控制台中運行並使用短語“我看到了一只藍鳥”時。 打印如下(變量供參考):
words = ['I', 'saw', 'a', 'blue', 'bird.']
wordCount_text_length = [1, 3, 1, 4, 4]
word_count = [2, 1, 2, 2, 2]
我被卡住了,因為 1.) 它將標點符號計算為字符串的一部分。 2.) 如何創建一個循環來創建將采用單詞長度/計數一次並移動到下一個長度的列表列表?
您可以使用.isalpha()
過濾掉標點符號:
text = input('Please enter a paragaph of regular English text: \n').split()
new_text = [''.join(b for b in i if b.isalpha()) for i in text]
final_list = [[len(i), ''.join(new_text).count(i.lower())] for i in new_text]
使用“我看到一只藍鳥。”的輸入,最終輸出是:
[[1, 1], [3, 1], [1, 2], [4, 1], [4, 1]]
您還可以使用字典來幫助可視化您的輸出:
final_list = {i.lower():[len(i), ''.join(new_text).count(i.lower())] for i in new_text}
輸出:
{'i': [1, 1], 'saw': [3, 1], 'a': [1, 2], 'blue': [4, 1], 'bird': [4, 1]}
我使用了一個字典,然后在最后把它變成了一個列表。 我還使用 .isalpha() 檢查了標點符號。 sorted(word_lengths.items())
如果您希望對最終列表進行排序,則在最后一行。
words = input().split()
word_lengths = {}
puncs = [',', '.']
for word in words:
y = word
if not y.isalpha(): y = y[:-1]
length = len(y)
try: word_lengths[length] += 1
except KeyError: word_lengths[length] = 1
print([[k, v] for k, v in word_lengths.items()])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.