Python字符串索引
我有一个包含用户的文件:Python字符串索引,python,string,file,python-2.7,Python,String,File,Python 2.7,我有一个包含用户的文件: Sep 15 04:34:31 li146-252 sshd[13326]: Failed password for invalid user ronda from 212.58.111.170 port 42579 ssh2 Sep 15 04:34:33 li146-252 sshd[13328]: Failed password for invalid user romero from 212.58.111.170 port 42715 ssh2 Sep 15 0
Sep 15 04:34:31 li146-252 sshd[13326]: Failed password for invalid user ronda from 212.58.111.170 port 42579 ssh2
Sep 15 04:34:33 li146-252 sshd[13328]: Failed password for invalid user romero from 212.58.111.170 port 42715 ssh2
Sep 15 04:34:36 li146-252 sshd[13330]: Failed password for invalid user rom from 212.58.111.170 port 42838 ssh2
正在尝试使用字符串的索引方法打印文件中的用户,但该方法不起作用:
with open ('test.txt') as file:
for line in file.readlines():
lines = line.split()
string = ' '.join(lines)
print string.index('user')+1
它的作用是:
user
,并记住找到user的索引您可以只执行
print(第[10]行]
,而不是print(第[10]行])
。这假设名称将位于同一位置。我会这样做的
此外,如果您想更改日志中的名称,下面是如何更改的
file = open('tmp.txt', 'r')
new_file = []
for line in file.readlines(): # read the lines
line = (line.split(' '))
line[10] = 'vader' # edit the name
new_file.append(' '.join(line)) # store the changes to a variable
file = open('tmp.txt', 'w') # write the new log to file
[file.writelines(line) for line in new_file]
这将把紧随其后的所有用户名打印到字符串
user
with open('file') as f:
for line in f:
words = line.split()
print(words[words.index('user')+1])
这将打印出文件中包含的用户名。它假定用户名始终是行中第一个“user”实例后面的单词。小心处理任何不包含“user”一词的行,或将“user”作为行中最后一个词的行
keyword = 'user'
with open ('test.txt') as f:
for line in f.readlines():
words = line.split()
try:
index_user = words.index(keyword) + 1
print words[index_user]
except ValueError:
pass # line does not contain keyword
except IndexError:
pass # keyword is the last word in the line
它正是我期望它做的,定义“不工作”。
打印行。index('user')+1
如果您有一行,并且想要更改文本文件中的用户名,这是可能的吗?对不起,我不知道您的意思。。你能提供一个例子吗?如果你想用你脚本中的一个变量来改变用户呢?是的,举个例子。可能吗?
keyword = 'user'
with open ('test.txt') as f:
for line in f.readlines():
words = line.split()
try:
index_user = words.index(keyword) + 1
print words[index_user]
except ValueError:
pass # line does not contain keyword
except IndexError:
pass # keyword is the last word in the line