簡體   English   中英

在列表Python 3中查找替換字符串匹配

[英]Finding an replacing string matches in lists Python 3

我作為主持人自願加入一個經過改造的Minecraft社區,我們經常處理聊天記錄。 我正在構建一個程序來獲取服務器的聊天記錄,在其中查找匹配的用戶名並將其寫入新文件。 我目前使用的方式是,將文件提取,並將每一行轉換為一個列表項,我使用表達式對用戶名進行正則表達式,如果其中包含匹配項,則將該行寫入。 問題是,聊天記錄的格式是這樣的: BOTusername ,我想使用該程序在搜索之前剝離BOT部分(使末尾寫得更整潔)。

我知道當您使用f.read('file.txt')正常讀取文件時這是可能的,但我想知道是否可以使用列表來完成此操作。 是列表的示例。

到目前為止,我的代碼如下:

import os
import re
username = 'UsernameHere'
path = os.path.dirname(__file__)
with open('chatlogs.txt', 'r') as f:
    chatlogs = f.readlines()
print(chatlogs) # for debugging

# Checks the chatlogs for username matches
for line in chatlogs:
    if re.match('(.*)' + username + '(.*)', line):
        d = open('output.txt', 'a')
        d.write(line)

如果您的username變量始終看起來像“ BOTsomeusername”,則可以使用一些簡單的索引來去除前三個字符:

username = username[3:]

感謝Hoog為我指出正確的方向!

我將其與以下代碼一起使用:

for line in chatlogs:
    if re.match('(.*)' + username + '(.*)', line):
        d = open('output.txt', 'a')
        timestamp = line.split(']', 1)[0] + '] ' # includes the bracket that gets removed in the split operation
        message = line.split('] ', 1)[1][3:] # saves the remainder of the message after the third character (After BOT)
        d.write(timestamp + message)

暫無
暫無

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

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