[英]find out how many times does that inputed sign appear in the document
在這個程序中,我想打印一個文檔; 計算您在輸入部分要求的特定字符的行數和數量。 我想知道輸入的符號在文檔中出現了多少次。 但是程序返回與num_lines相同的數字,而數字不相同。 為什么呢? 如何使其工作以及獲得相同結果的其他方法是什么? 提前致謝!
file = open('notes.txt', 'r')
for i in file:
print (i)
num_lines = sum(1 for line in open('notes.txt'))
print('The number of lines in the document is:', num_lines)
signs=input('Input the sign you want to count:')
num_sign = sum(1 for signs in open('notes.txt'))
print('The number of signs in the document is:', num_sign) ```
當你寫:
for signs in open('notes.txt')
您覆蓋了之前聲明的變量signs
。
您可以將其替換為:
signs = input('Input the sign you want to count:')
num_sign = 0
for line in open('notes.txt'):
num_sign += line.count(signs)
我會這樣做:
signs = input('Input the sign you want to count:')
file = open('notes.txt', 'r')
f = file.read()
print('lines:', len(f.split('\n')))
print('signs:', f.count(signs))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.