首页 > 解决方案 > 从文件中获取不同的字符串并写入 .txt

问题描述

我正在尝试将文本文件 (.log) 中的行转换为 .txt 文档。

我需要将相同的数据放入我的 .txt 文件中。但线路本身有时会有所不同。从我在互联网上看到的情况来看,通常使用一种可以预测生产线的模式来完成。

1525:22Player 11 spawned with userinfo: \team\b\forcepowers\0-5-030310001013001131\ip\46.98.134.211:24806\rate\25000\snaps\40\cg_predictItems\1\char_color_blue\34\char_color_green\34\char_color_red\34\color1\65507\color2\14942463\color3\2949375\color4\2949375\handicap\100\jp\0\model\desann/default\name\Faybell\pbindicator\1\saber1\saber_malgus_broken\saber2\none\sex\male\ja_guid\420D990471FC7EB6B3EEA94045F739B7\teamoverlay\1

我正在使用的线路通常看起来像这样。我试图收集的数据是:

\ip\0.0.0.0
\name\NickName_of_the_player
\ja_guid\420D990471FC7EB6B3EEA94045F739B7

并在 .txt 文件中打印这些数据。这是我当前的代码。如上所述,我不确定在谷歌研究中使用什么关键字。以及如何调用它(因为字符串不一样?)

我一直在环顾四周,我所做的大部分测试都允许我做一些事情,但我还不能像上面解释的那样做。所以我希望在这里得到指导 :) (对不起,如果我是菜鸟,我很了解它是如何工作的,我只是在学校没有学过语言,我主要是写小脚本,而且通常它们工作得很好,这次这更难)

def readLog(filename):

  with open(filename,'r') as eventLog:
    data = eventLog.read()
    dataList = data.splitlines()
  
    return dataList


    eventLog = readLog('games.log')

标签: pythonstringfileparsinglogging

解决方案


您需要以“原始”模式而不是字符串形式读取文件。从磁盘读取文件时,使用open(filename,'rb'). 为了使用你的例子,我跑了

text_input = r"1525:22Player 11 spawned with userinfo: \team\b\forcepowers\0-5-030310001013001131\ip\46.98.134.211:24806\rate\25000\snaps\40\cg_predictItems\1\char_color_blue\34\char_color_green\34\char_color_red\34\color1\65507\color2\14942463\color3\2949375\color4\2949375\handicap\100\jp\0\model\desann/default\name\Faybell\pbindicator\1\saber1\saber_malgus_broken\saber2\none\sex\male\ja_guid\420D990471FC7EB6B3EEA94045F739B7\teamoverlay\1"
text_as_array = text_input.split('\\')

您需要知道哪些列包含您关心的字符串。例如,

with open('output.dat','w') as fil:
    fil.write(text_as_array[6])

您可以从示例字符串中计算出这些数组位置

>>> text_as_array[6]
'46.98.134.211:24806'
>>> text_as_array[34]
'Faybell'
>>> text_as_array[44]
'420D990471FC7EB6B3EEA94045F739B7'

如果列位置不一致但键值对总是相邻的,我们可以利用它

>>> text_as_array.index("ip")
5
>>> text_as_array[text_as_array.index("ip")+1]
'46.98.134.211:24806'

推荐阅读