量「:」(?)在一個.txt,因爲這樣:如何獲得我與劃分不同的單詞列表中的「弦」和打印
banana:pinapple
apple:grapes
orange:nuts
...
我怎樣才能得到數在分號的左邊有一個單詞的行並打印該數字?
我用這給它們分開:
string1, string2 = line.split(':')
我想打印數量排序是這樣的:
print(number of lines where there exists is a string1)
量「:」(?)在一個.txt,因爲這樣:如何獲得我與劃分不同的單詞列表中的「弦」和打印
banana:pinapple
apple:grapes
orange:nuts
...
我怎樣才能得到數在分號的左邊有一個單詞的行並打印該數字?
我用這給它們分開:
string1, string2 = line.split(':')
我想打印數量排序是這樣的:
print(number of lines where there exists is a string1)
剛拿到的行數,而不是像這樣:
with open(listname) as list:
lines = len(list.readlines())
你應該在將來更清楚地瞭解你的問題約束。 「左手邊」無關緊要。 –
@aryamccarthy是的,對不起,感謝嘗試幫助! – Jesper
count = 0
for line in f:
string1, string2 = line.split(':')
if string1:
count += 1
print(count)
你的問題詢問有關的單詞數在左邊,這正是這個重點。這處理行:foo
的情況。儘管如此,你還沒有建議有沒有冒號的線路或者多於一條的線路。另外,你還沒有說過左邊會有多個單詞。我選擇忽略這些情況,因爲你沒有表明它們的存在。
基本上只計算一個文本文件中的行號也會做什麼? – Aditya
這處理行是':foo'的情況。 –
@aryamccarthy雖然這是一個有效的案例? OP的例子沒有顯示任何指示:「foo」或「foo:」,「:」存在。 – rbaleksandar
fileName = 'myfile.txt'
counterDict = {}
with open(fileName,'r') as fh:
for line in fh:
left,right = line.rstrip('\n').split(':')
counterDict[left] = counterDict.get(left,0)+1
print(counterDict)
#貓myfile.txt複製
banana:pinapple
apple:grapes
orange:nuts
banana:pinapple
apple:grapes
orange:nuts
banana:pinapple
apple:grapes
orange:nuts
#結果
{'banana':3,'apple':3,'orange':3}
所以我不知道我的理解基礎上提供的所有回答你的問題。你想知道的是如何計算文本文件中的行數?
是的,我看到你說過「在冒號的左邊有一個詞」,但是爲什麼你會冒出一個冒號排除任何其他文本?你說你的程序以這樣的方式編寫文本:「example」是正確的嗎?
如果是這樣的話,除非你故意輸入任何東西,否則不會在任何其他文本上出現冒號。
def get_total_lines(self, path):
counter = 0
try:
if os.path.isfile(path):
with open(path, 'r') as inFile:
for i in enumerate(inFile):
counter = counter + 1
return str(counter)
elif not os.path.isfile(path):
print("Error: The file you're attempting to read does not exist, aborting reading process...")
except IOError as exception:
raise IOError('%s: %s' % (path, exception.strerror))
return None
那一定錯誤檢查的一些基本形式,這裏是一個與出它。
def get_total_lines(self, path):
counter = 0
with open(path, 'r') as inFile:
for i in enumerate(inFile):
counter = counter + 1
return str(counter) # could be int or w/e else you want it to be
這將計數行,如果你想剝離一個單詞或冒號,它可以很容易地適應做到這一點。
簡單的方式 - 拆分後,將它們組合起來作爲一個單獨的列表,並使用計數器 – Aditya
@aryamccarthy我想打印,所以我已經試過的打印量( len(string1))但我真的不知道要搜索什麼。 – Jesper
其他有點容易的方法將使用默認鍵實現的字典 – Aditya