简体   繁体   English

使用Python从文本中打印一些所需的行

[英]Print a few wanted lines from text with Python

I would like to print out the lines that are in bold. 我想打印出粗体的行。 I tried using .find() to match with the string "X-Sieve" so that the loop would revolve only before it matches with the text, but it doesn't seem to work. 我尝试使用.find()与字符串“ X-Sieve”匹配,以便循环仅在与文本匹配之前旋转,但似乎不起作用。 How can I do it? 我该怎么做?

所需行突出显示

Disclaimer: 免责声明:

First of all, What is your current output? 首先,您当前的输出是多少? 'Not working' is not enough for us to understand. “不工作”还不足以让我们理解。 Second, try to use real code in your questions rather than images - people don't necessarily want to manually copy your code to test. 其次,尝试在问题中使用真实的代码,而不要使用图像-人们不一定要手动复制您的代码以进行测试。

Answer: 回答:

In case your code prints all lines in the moment, just add the following before the print statement at the bottom of your code: 万一您的代码现在打印所有行,只需在代码底部的print语句之前添加以下内容:

if 'X-Sieve' in hand:
   break
else:
   print hand

I'm not too sure what you're going for here. 我不太确定您要在这里做什么。
Like sudonym said, please paste your code, your text file and your output. 就像sudonym所说的那样,请粘贴您的代码,文本文件和输出。

If those are the first few lines of the file, and it's always going to use those lines, you could apply this barebones script: 如果这些是文件的前几行,并且将始终使用这些行,则可以应用以下准系统脚本:

 #open foo.txt and assign it the var file1 file1 = open("foo.txt", "r") #read all the lines in the document, assigning the lines variable here lines = file1.readlines() #Printing the first 3 lines, remember python starts at 0 print(lines[0]) print(lines[1]) print(lines[2]) #close the file from memory file1.close() 

Foo.txt has the following data: Foo.txt具有以下数据:

asdf theline2 welcometohell what up

The python script outputs the following: python脚本输出以下内容:

asdf theline2 welcometohell

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

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