从文件中获取不同的字符串并写入.txt

2024-05-18 23:32:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将文本文件(.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')

Tags: 文件数据nameiptxtlogwith模式
1条回答
网友
1楼 · 发布于 2024-05-18 23:32:43

您需要以“原始”模式读取文件,而不是以字符串的形式读取。从磁盘读取文件时,请使用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'

相关问题 更多 >

    热门问题