Python字符串索引

2024-05-19 11:31:43 发布

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

我有一个包含用户的文件:

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

Tags: 方法用户fromssh2forportlinepassword
3条回答

这将把紧跟其后的所有用户名打印到字符串user。你知道吗

with open('file') as f:
    for line in f:
        words = line.split()
        print(words[words.index('user')+1])

它的作用是:

  1. 查看文件中的每一行

  2. 根据该行原始字符串版本中的空白,将该行拆分为项目列表

  3. 在新创建的列表项中搜索user,并记住找到user的索引。

  4. 在找到用户的索引中添加1并打印该项


with open('test.txt') as file:
    for line in file.readlines():
        line = line.split(' ')  # convert the string to a list
        print(line[line.index('user')+1])  # find 'user' in the list and print the item that comes after that

代替print(line[10])你可以只做print(line[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”实例后面的单词。注意处理任何不包含单词“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

相关问题 更多 >

    热门问题