簡體   English   中英

Python - 從大型 .csv 文件中的文本文件中搜索字符串列表

[英]Python - Search a list of strings from a text file in a large .csv file

抱歉,我可能在這里犯了一大堆錯誤,但我正在嘗試使用文件 (justgenes.txt) 中的字符串列表搜索大型 CSV 文件,並返回包含 justgenes 列表中的字符串的行。

我一直在很大程度上使用 BASH,但是我的代碼占用了超過 100GB 的內存並且崩潰了:

grep -f justgenes.txt allDandHunique.csv > HPCgenesandbugs.csv

因此,我試圖用 python 來做,假設它會更有效率,但我對它知之甚少。

我使用這個代碼(我從網上抓取的),但最后得到一個空文件:

data = open('allDandHunique.csv')
                
with open('justgenes.txt', "r+") as file1:
    fileline1= file1.readlines()
    for x in data: # <--- Loop through the list to check      
        for line in fileline1: # <--- Loop through each line
            if x in line:
                 print(x)

justgenes 文件如下所示:

1A0N_B
1A1A_A
1A4I_A
1A5Y_A
1ACO_A
1AGN_A
1AGS_A
1AJE_A
1AJJ_A
1AP0_A
1APQ_A

雖然 csv 看起來像這樣:

"0403181A:PDB=1BP2,2BPP",
"0403181A:PDB=1BP2,2BPP",,,
"0706243A:PDB=1HOE,2AIT,3AIT,4AIT",
"0706243A:PDB=1HOE,2AIT,3AIT,4AIT",,,
"1309311A:PDB=1EMD,2CMD",
"1309311A:PDB=1EMD,2CMD",,,
"1513188A:PDB=1BBC,1POD",
"1513188A:PDB=1BBC,1POD",,,
0308206A,
0308206A,,,
0308221A,
0308221A,,,
0308230A,
0308230A,,,

任何幫助將不勝感激。

我會用熊貓來完成這個。

嘗試類似:

import pandas as pd

df = pd.read_csv('allDandHunique.csv')

with open('justgenes.txt', "r+") as file1:
    fileline1= file1.readlines()
    for x in fileline1: 
      for col in df:
         if col.str.contains(x, regex=False):
             ##do something here##

如果在讀取文件時得到一個空白文件,我會檢查並確保路徑正確。

由於我沒有這些文件,因此我無法自己測試,但我認為此代碼可能會有所幫助。

data = open('allDandHunique.csv')
        
for x in data: # <--- Loop through the list to check      
    with open('justgenes.txt', "r+") as file1:
        fileline1= file1.readlines()
        for line in fileline1: # <--- Loop through each line
            if x in line:
                    print(x)

對於x in data每個x in data您必須遍歷 file1 中的所有行。 如果我沒有錯,你需要為每次迭代打開你的文件,否則,當你到達 EOF 時它什么都不返回。

import csv

with open('justGenes') as infile:
    searchTargets = set(line.strip() for line in infile)


with open('allDandHunique.csv') as infile:
    for row in csv.reader(infile):
        if any(target in row for target in searchTargets):
            print(row)

暫無
暫無

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

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