簡體   English   中英

計算文本文件中特定值的出現次數

[英]Counting the number of occurrences of a specific value in a text file

我有30列的文本文件。 並使用python,我想根據第3列中的值計算行數。實際上,在第3列中出現了“水泥”多少次。這些列也沒有名稱(或標題)。

count = 0
with open('first_basic.txt') as infile: 
    for line in infile: 
        for j in (line.split()[3]): 
            if j == "cement": 
                count += 1

謝謝

您正在檢查每行第三列(單詞)的每個字符,以檢查其是否等於水泥:

'c' == 'cement' => False
'e' == 'cement' => False
etc.

你應該更換

for j in (line.split()[2]): 
    if j == "cement": 
        count += 1

if line.split()[2] == "cement": 
    count += 1

完整代碼:

count = 0
with open('first_basic.txt') as infile: 
    for line in infile: 
        if line.split()[2] == "cement": 
            count += 1
print count

假設您為匹配項定義了謂詞函數:

def match(line):
    return line.split()[2] == 'cement'

您可以將此謂詞與filter一起使用,並計算匹配行的數量:

with open('first_basic.txt') as infile: 
    print(len(list(filter(match, infile.readlines()))))

但這需要內存才能首先建立list 使用生成器可能會更快,並且不需要列表的內存:

    print(sum(1 for line in infile if match(line))

數組的起始位置為0,而不是1。因此,如果要獲取['DUMMY', 'DUMMY', 'CEMENT', 'NOT_CEMENT']的第三個元素,則必須處於[2]位置。 因為[3]位置是'NOT_CEMENT'。

第二,是逐個字母,而不是逐行。 您排隊的行。

因此,要解決您的代碼更改:

if line.split()[2] == "cement": #Change here for two
    count += 1

但是您可以采用以下干凈的解決方案:

with open('first_basic.txt') as infile: 
    map(lambda x: x.split()[2], infile).count('cement')

讓我們解釋一下代碼。

map()負責做與for相同的事情。 它將在可迭代對象的所有元素中進行迭代。 並為每個元素應用一個函數。

使用的功能是這樣的:

lambda x: x.split()[2]

這是執行此操作的功能方法:

def function(x):
    return x.split()[2]

但是為什么我使用lambda? 有一個簡單的答案,我將不再調用此函數。 因此,我不需要在內存中使用該函數,因此我在Python中使用了lambda AKA匿名函數。

您可以在此處查看有關map函數和lambda函數的信息

我希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM