除了列印串列外,一切正常,我嘗試了多種方法,,,rstrip()等splitline()。replace()但也許我沒有正確使用它們。我對使用字典還很陌生,所以我希望能針對當前問題提供一些指導。
txt 檔案(應該已經是串列形式):
Shopping List
ITEM 1000: Frozen Burgers
ITEM 1001: Bread
ITEM 1002: Frozen Burgers
ITEM 1003: Mayonnaise
ITEM 1004: Bread
ITEM 1005: Frozen Burgers
ITEM 1006: Mustard
ITEM 1007: Tomato
ITEM 1008: Tomato
代碼:
from collections import Counter
def get_items():
print("""Items that repeat twice or more in the lists:
Item Name Repeat Times
------------------------------""")
item_count = Counter()
with open('Shopping_List.txt') as f:
for line in f.readlines()[1:]:
item_count.update([line[11:]])
print('\r',*item_count.most_common(3),sep='\n')
def get_dictionaries(textfile):
items = {}
numbers = {}
FIRST_NUM = 1000
with open(textfile) as f:
for lines in f.readlines()[1:]:
numbers[FIRST_NUM]=lines.lstrip()[11:]
items[lines.lstrip()[11:]]=items.setdefault(lines.lstrip()[11:],0) 1
FIRST_NUM = 1
return items,numbers
get_items()
uj5u.com熱心網友回復:
正確的解決方案是使用計算機可讀的輸入檔案格式,這樣您就不必撰寫自己的決議器。
不過,這是對您的代碼的快速重構。
from collections import Counter
def get_items():
print("""Items that repeat twice or more in the lists:
Item Name Repeat Times
------------------------------""")
item_count = Counter()
with open('Shopping_List.txt') as f:
for idx, line in enumerate(f):
if idx == 0:
next
item_count.update([line[11:].rstrip('\n')])
for x in item_count.most_common(3):
print(' {0:16} {1}'.format(*x))
get_items()
我洗掉了未使用的功能。主要的變化是.rstrip('\n')雖然還要注意行的列印和迭代是如何重構的。
uj5u.com熱心網友回復:
您可以像這樣列印行:
def get_items():
print(
"""Items that repeat twice or more in the lists:
Item Name Repeat Times
------------------------------"""
)
item_count = Counter()
with open("1.txt") as f:
for line in f.readlines()[1:]:
item_count.update([line[11:]])
for item, count in item_count.most_common(): # <--- Here.
print(f"{item.rstrip():>15} {count:>6}")
這將列印以下內容:
Items that repeat twice or more in the lists:
Item Name Repeat Times
------------------------------
Frozen Burgers 3
Bread 2
Mayonnaise 1
Mustard 1
Tomato 1
Tomato 1
uj5u.com熱心網友回復:
您可以對讀取的每個字串進行簡單檢查。
if StringExample[-1:] == "\n":
StringExample = StringExample[:-1]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/524445.html
