简体   繁体   English

如何在Python中结束循环?

[英]How to end for loop in Python?

I'm new to programming and am playing around with Python scripting. 我是编程新手,正在玩Python脚本。

I'm trying to write a Python script that will read a text file and print to screen, search for a word, and every time it finds the word, to split the data of that line. 我正在尝试编写一个Python脚本,它将读取文本文件并打印到屏幕,搜索单词,每次找到单词时,都要分割该行的数据。

The test.txt file looks something like: test.txt文件如下所示:

ape bear cat dog ape elephant frog giraffe ape horse iguana jaguar

I want the end result on screen to look like: 我希望屏幕上的最终结果如下:

ape bear cat dog
ape elephant frog giraffe
ape horse iguana jaguar

My code so far: 我的代码到目前为止:

file = "test.txt"
read_file = open(file, "r")
with read_file as data:
    read_file.read()
    print(data)
    word = "ape"
    for word in data:
        data.split()
        print(data)

I made the file a variable because I intend to use it many different times in the script. 我把文件变成了变量,因为我打算在脚本中使用它很多次。

When I tested the code, the for loop didn't stop after one loop. 当我测试代码时,for循环在一个循环后没有停止。 It eventually ended, but I'm sure if it was the code or program automatically ends infinite loops. 它最终结束了,但我确定是否代码或程序自动结束无限循环。

How do I edit the code so that the for loop will stop once it reaches the end of the file? 如何编辑代码,以便for循环一旦到达文件末尾就会停止? And is there a more correct way to write this code? 是否有更正确的方法来编写此代码?

Again, this is just an example file, not my actual file. 同样,这只是一个示例文件,而不是我的实际文件。 Thanks! 谢谢!

>>> f = open("test.txt")
>>> a = f.read()
>>> f.close()
>>> a = a.replace("ape", "\nape")
>>> print(a)

ape bear cat dog
ape elephant frog giraffe
ape horse iguana jaguar

Try this, it does exactly what you intend: 试试这个,它完全符合你的意图:

file = "test.txt"
word = 'ape'
read_file = open(file, "r")
with read_file as data:
    for line in data:
        sp = line.split(word)
        for s in sp:
            if s:
                print(word + s)
fileName = "test.txt"
read_file = open(fileName, "r")
with read_file as open_file:
    data = open_file.read().rstrip()
    keyword = "ape"
    data = ' '.join(["\n"*(word == keyword) + word for word in data.split()]).strip()
#   data = data.replace(keyword, "\n"+keyword).strip()
    print(data)

OUTPUT: OUTPUT:

# ape bear cat dog 
# ape elephant frog giraffe 
# ape horse iguana jaguar

Assuming that you're trying to learn about control flow and are not trying anything fancy with regular expressions or replacing the contents... 假设您正在尝试了解控制流,并且没有尝试使用正则表达式或替换内容...

It looks like you are trying to do something like this (comments inline): 看来您正在尝试执行以下操作(内联注释):

filename = 'test.txt'               # `file` is a Python built-in
with open(filename, 'r') as data:   # Open the file and close it when we're done
    for line in data:               # This will read one line at a time and exit the loop at EOF
        for word in line.strip().split():  # Strip off the newline and split the line into words
            if word == 'ape':       # If we've found our keyword
                print               #     Then Print a newline
            print word,             # Print every word, without a trailing newline

For Python 3, you'll need to change the syntax ever-so-slightly: 对于Python 3,您需要稍微更改语法:

filename = 'test.txt'
with open(filename, 'r') as data:
    for line in data: 
        for word in line.strip().split():
            if word == 'ape':
                print()
            print(word, end=' ')

The test.txt file looks something like: test.txt文件如下所示:

 ape bear cat dog ape elephant frog giraffe ape horse iguana jaguar 

I want the end result on screen to look like: 我希望屏幕上的最终结果如下:

 ape bear cat dog ape elephant frog giraffe ape horse iguana jaguar 

So you want every occurrence of 'ape' to be at the start of a line. 所以你希望'ape'的每一次出现都在一行的开头。

My code so far: 我的代码到目前为止:

 file = "test.txt" read_file = open(file, "r") with read_file as data: 

There is no point in splitting these two up. 将这两者分开是没有意义的。 If with is done with the file, it is closed and has to be open() ed again. 如果with与文件来完成,它是封闭的,且必须open()再编。

So just do 所以做

with open(file, "r") as data:

BTW, in your code, read_file and data are the same. 顺便说一下,在你的代码中, read_filedata是一样的。

  read_file.read() 

So you read the whole file into memory and discard the result. 因此,您将整个文件读入内存并丢弃结果。

  print(data) 

Print the file object. 打印文件对象。

  word = "ape" 

Assigns... 分配...

  for word in data: 

... and immediately discards it again. ......然后立即丢弃它。

  data.split() 

Splits the data and discards the result. 拆分数据并丢弃结果。

  print(data) 

Prints the file object again. 再次打印文件对象。

But, as you have read the whole file, the for loop probably didn't run at all. 但是,当你读完整个文件时, for循环可能根本没有运行。

Improvements: 改进:

filename = "test.txt" # file is a builtin function
hotword = "ape"
with open(filename, "r") as read_file:
    for line in read_file:
        parts = line.split(hotword)
        if not parts[0]: # starts with the hotword, so 1st part is empty
            del parts[0]
        print ("\n" + ape).join(parts)

I made the file a variable because I intend to use it many different times in the script. 我把文件变成了变量,因为我打算在脚本中使用它很多次。

For the name it is ok, but the open file cannot be recycled, as with closes it. 对于名字这是确定的,但打开的文件无法被回收,如with其关闭。

When I tested the code, the for loop didn't stop after one loop. 当我测试代码时,for循环在一个循环后没有停止。

Sure? 当然? What did it print? 什么印刷?

import re

file = "test.txt"
for line in open(file, 'r'):
    if(re.search('ape', line )):
        print(line)

You can use re.sub to escape the any word found not at the beginning of the line, and put a newline character before it, so you can use the following code. 您可以使用re.sub来转义未在行首找到的任何单词,并在其前面放置换行符,因此可以使用以下代码。

Note that this looks for whole-words - eg, grape won't be matched with ape (unlike the str.replace solution offered): 请注意,这会查找整个单词 - 例如, grape将不会与ape匹配(与提供的str.replace解决方案不同):

import re

word = 'ape'
with open('yourfile') as fin:
    line = next(fin, '')
    print(re.sub(r'[^\b]({0}\s+)'.format(re.escape(word)), r'\n\1', line))

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

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