简体   繁体   English

在文件的特定行中查找字符

[英]Finding the Characters in a Specific Line in a File

I am trying to find the characters in one specific line of my code. 我正在尝试在代码的特定行中找到字符。 Say the line is 4. 说这行是4。

My file consists of: 我的文件包括:

1. randomname
2. randomname
3. 
4. 34
5. 12202018

My code consists of: 我的代码包括:

with open('/Users/eviemcmahan/PycharmProjects/eCYBERMISSION/eviemcmahan', 'r') as my_file:

data = my_file.readline(4)
characters = 0

for data in my_file:
    words = data.split(" ")
    for i in words:
        characters += len(i)

print(characters)

I am not getting an error, I am just getting the number "34" 我没有收到错误,只是得到了数字“ 34”

I would appreciate any help on how to get a correct amount of characters for line 4. 对于在第4行获得正确数量的字符的任何帮助,我将不胜感激。

my_file.readline(4) does not read the 4th line, instead reads the next line but only the 4 firsts characters. my_file.readline(4)不读取第4行,而是读取下一行,而仅读取4个首字符。 To read a specific line you need to, for example, read all the lines and put them in a list. 要读取特定行,例如,您需要读取所有行并将它们放在列表中。 Then is easy to get the line you want. 然后很容易就能得到您想要的线。 You could also read line by line and stop whenever you find yourself in the line you desired. 您也可以逐行阅读并在遇到所需行时停下来。

Going with the first approach and using the count method of strings, it is straight-forward to count any character at a specific line. 与第一种方法一起使用字符串的count方法,直接计算特定行上的任何字符都是很简单的。 For example: 例如:

line_number = 3 # Starts with 0
with open('test.txt', 'r') as my_file:
  lines = my_file.readlines() # List containing all the lines as elements of the list
print(lines[line_number ].count('0')) # 0
print(lines[line_number ].count('4')) # 2

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

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