gpt4 book ai didi

python - 需要一个字符缓冲区对象 : Python 2. 7

转载 作者:行者123 更新时间:2023-12-01 04:57:26 24 4
gpt4 key购买 nike

我试图从文本文件中获取一行的第三个元素,但在尝试时出现上述错误。以下是我的代码

def time_difference():
button_pressed = ''
command = ''
b_p_c_s = ''
next_line_to_command = ''
test = ''
print "\n\033[32m-- TIME DIFFERENCES --\033[0m\n"
with open('messages', 'r') as searchfile:
for line in searchfile:
if ':Button' and 'pressed' in line:
button_pressed = str(line)
with open('buttonpress_and_commandstarted','a') as buttonpressed:
buttonpressed.write(button_pressed)
buttonpressed.close()
elif 'Command' and 'started' in line:
command = str(line)
with open('buttonpress_and_commandstarted','a') as commandstarted:
commandstarted.write(command)
buttonpressed.close()
with open('buttonpress_and_commandstarted','a') as file_opened:
file_opened.close()
with open('buttonpress_and_commandstarted','r') as buttonpress_commandstarted:
b_p_c_s = buttonpress_commandstarted.read()
print b_p_c_s
buttonpress_commandstarted.close()
print "\n\033[32m-- NEXT TO KEYWORDS --\033[0m\n"
with open('buttonpress_and_commandstarted', 'r') as searchfile:
for line in searchfile:
try:
if 'Command' and 'started' in line:
next_line_to_command = searchfile.next()
test = str(next_line_to_command)
print next_line_to_command
except StopIteration:
pass
print "\n\033[32m-- TIME --\033[0m\n"
test.split(3)
searchfile.close()

我明白了

Traceback (most recent call last):
File "./gui-analyser.py", line 114, in <module>
time_difference()
File "./gui-analyser.py", line 106, in time_difference
test.split(3)
TypeError: expected a character buffer object

我的目的是获取行中空格之后的第三个元素

Jan 01 07:24:07 AMIRA-134500021 user.notice butler[775]: LOG:200708a0:12:Button 11 pressed.

在本例中07:24:07

我看到一些论坛,因为只能使用字符串来完成分割,所以我将变量转换为字符串,但我遇到了这个问题。任何指导都会非常有帮助。

最佳答案

str.split() 将一个字符串作为其第一个参数来分割输入字符串。您正在尝试向其传递一个整数。

如果您想按空格分割并从结果中挑选出特定元素,则对返回的列表进行索引:

third_element = test.split()[2]

其中Python使用从0开始的索引,因此使用2作为索引来访问第三个元素。请注意,这会返回值,因此您可能需要存储该结果。

关于python - 需要一个字符缓冲区对象 : Python 2. 7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27067011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com