简体   繁体   English

在文本文件中寻找行号和行号

[英]looking for line and linenumber in text file

I'm making a extra function for my chat program which allows you to register by typing a specific command that makes the host script save your peername and a name you insert in the terminal, its saved like this 57883:Jack in a txt file (names.txt) on the host machine. 我为聊天程序做了一个额外的功能,该功能允许您键入一个特定的命令进行注册,该命令使主机脚本保存您的对等名称和您在终端中插入的名称,它的保存如下57883:Jack在txt文件中(在主机上)。 if a number of people have registered it'll look like this 如果有很多人注册,它将看起来像这样

57883:jack 
57884:bob
57885:connor
57886:james
57887:zzhshsb93838
57887:ryan

when someone sends a message i want to know if his/her name is registered and if so, get the name to send to the client, so instead of seeing the peername the client will see the name of the person sending the message. 当某人发送消息时,我想知道他/她的姓名是否已注册,如果已注册,请将该名称发送给客户端,这样,客户端无需看到同名,便会看到发送消息的人的姓名。 in order to do that i need to know if the peername is in the file and if so; 为了做到这一点,我需要知道对等名称是否在文件中,如果是; where in the file, in which line. 文件中的哪一行。 i've got this so far: 到目前为止,我已经做到了:

 peer = sock.getpeername()
 with open('names.txt', 'r') as d:
     lines = d.readlines()
     for peer in lines:

and i don't know how to find out in which line it was found, and when i know that how to seperate 57883 and ack and select jack and save it. 而且我不知道如何找出在哪条线找到的时间,何时我知道如何分开57883和ack并选择jack并保存。 Cheers! 干杯!

with open("names.txt", "r") as f:
    for i, line in enumerate(f):
        numb, name = line.rstrip().split(":")
        print i, numb, name

You can ask Python to provide a tuple of line number and line content for each line of the file (see enumerate(f) ). 您可以要求Python为文件的每一行提供行号行内容的元组(请参见enumerate(f) )。 Then you remove the line terminator (see line.rstrip() ) and split the line to parts separated by the provided character (see split(":") ). 然后,删除行终止符(请参阅line.rstrip() ),并将行拆分为由提供的字符分隔的部分(请参见split(":") )。 You have all three components available then. 然后,您将拥有所有三个组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM