鍍金池/ 問答/Python  HTML/ python3 特定行判斷讀取合并

python3 特定行判斷讀取合并

我有一個(gè)要處理的 txt 文件 test.txt

內(nèi)容是:

>列表名字
xxxxxxxxxxxxxxxx
xxxxxxxxxxxx
xxxx
>列表名字2
  xxxxxxxxxxxx
xxxx

要做的處理是對(duì) 每個(gè)列表名字 下的 所有行 進(jìn)行 某字符出現(xiàn)次數(shù) 的統(tǒng)計(jì)

我使用的讀取方法是:

def ratio(string):
    """讀取字符串計(jì)算比例的函數(shù)"""
    # ...

with open('test.txt', 'r') as f:
    for line in f:
        line = line.strip()
        if line.startswith('>'):  # 判斷開頭是否為>
            name = line[1:]       # 去掉>
        else:
            r = ratio(line)
            list1.append(name)
            list1.append(r)
            count.append(list1)   # count 這個(gè)列表包含了子集
            
# 跳出for后, 對(duì)count這個(gè)列表依照ratio進(jìn)行排序

print(count[-1])                  # 輸出count[-1]

我在 sampledata 時(shí)沒有考慮到 xxxxxxxxxxxxx 有很多行,現(xiàn)在不懂的做法是如何在這個(gè)基礎(chǔ)上將 xxx 行全部拼起來而不改變?cè)械乃悸罚ㄎ抑荒芟氲竭@個(gè)了),或提供別的更快捷的思路。

請(qǐng)各位大大指教,謝謝。

編者: 我盡量依照你的意思整理了一下資訊, 但很多地方還是很模糊, 也許你可以補(bǔ)充一下...
回答
編輯回答
寫榮

看描述,似乎含有「列表名字」的行總是以>開頭的?
那么兩個(gè)>之間的內(nèi)容就是列表名字 + 行內(nèi)容了吧。

代碼思路如下,沒有實(shí)際跑過:

current_content = ''
current_name = ''

for line in f:
    line = line.strip()
    if line.startswith('>'):  # 判斷開頭是否為 >
        name = line[1:]       # 去掉 >
        if current_content:
            # 處理當(dāng)前的內(nèi)容
            r = ratio(current_content)
            count.append((current_name, r))  # 將 tuple 插入 list, 此時(shí) current_name 尚未更新
        current_name = name  # 更新 current_name
        current_content = '' # 重置 current_content, 準(zhǔn)備記錄新的內(nèi)容
    else:
        current_content += line
2018年3月27日 06:24
編輯回答
陪她鬧

統(tǒng)計(jì)ATGC含量?

2018年4月6日 03:52