在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

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

python3 特定行判斷讀取合并

我有一個要處理的 txt 文件 test.txt

內(nèi)容是:

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

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

我使用的讀取方法是:

def ratio(string):
    """讀取字符串計算比例的函數(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 這個列表包含了子集
            
# 跳出for后, 對count這個列表依照ratio進行排序

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

我在 sampledata 時沒有考慮到 xxxxxxxxxxxxx 有很多行,現(xiàn)在不懂的做法是如何在這個基礎(chǔ)上將 xxx 行全部拼起來而不改變原有的思路(我只能想到這個了),或提供別的更快捷的思路。

請各位大大指教,謝謝。

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

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

代碼思路如下,沒有實際跑過:

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, 此時 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)計ATGC含量?

2018年4月6日 03:52