Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 views
in Technique[技术] by (71.8m points)

python - Don't understand some lines of code that reads a file

This is code which reads a file "jason.txt" and count how many of each “category” of each image there are.

The file data which I am using can be found at: http://www.practicepython.org/assets/Training_01.txt

counter_dict = {}

with open('jason.txt') as f:
   line = f.readline()

   while line:
     line = line[3:-26]

     if line in counter_dict:
         counter_dict[line] += 1

     else:
         counter_dict[line] = 1

     line = f.readline()

print(counter_dict)

Can someone explain what this line is doing:

line = line[3:-26]

And why are we using this line twice:

line = f.readline()
question from:https://stackoverflow.com/questions/65858092/dont-understand-some-lines-of-code-that-reads-a-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an example line from your file:

/a/abbey/sun_aqswjsnjlrfzzhiz.jpg

This gets read into the line variable by line = f.readline() so the while loop doesn't exit right away because of the empty line variable.

Then in the while loop line = line[3:-26] crops down the first 3 characters and the last 26 characters (because it is a line of a file, you need to count the return character at the end of each line, hence 26 instead of 25) so for this line your line variable will hold this: abbey.

The if statement in the while loop:

 if line in counter_dict:
         counter_dict[line] += 1

     else:
         counter_dict[line] = 1

If the value of the line variable which holds abbey at this point is found in the counter_dict than increments its value by 1 in the dictionary. If it is not found than adds it to the dictionary with value set to 1.

The last thing the while loop does is to get the next line from the file with line = f.readline().

It will keep doing that until there is no next line and than it prints the resulting json file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...