简体   繁体   English

如何在文件python中提取文本

[英]How to extract a text in a file python

How to extract a text in a file with python. 如何使用python提取文件中的文本。 - A text begin with chaine. -文本以chaine开头。

My code is 我的代码是

fichier= open("Service.txt", "r")
for ligne in fichier:
  if ligne==chaine:
  #What do I do ? 
fichier.close()

You have to check in operator with string. 您必须使用字符串签in运算符。

Like 喜欢

>>> a = "cheine is good"
>>> "cheine" in a
True

So your code must be like. 因此,您的代码必须像。

fichier= open("Service.txt", "r")
for ligne in fichier:
  if chaine in ligne:
  #What do I do ? 
fichier.close()

If you have to check start only in line, then you can check ligne.startswith . 如果您必须仅检查ligne.startswith ,则可以检查ligne.startswith

with open("Service.txt", "r") as f:
    lines = f.readlines()
chaines = [line for line in lines if line.startswith("chaine")]
for chaine in chaines:
    print("Some chaine, whatever that is", chaine)

This uses a list comprehension, the if part will filter out any line that doesn't start with "chaine" . 这使用列表"chaine"if部分将过滤掉所有不以"chaine"开头的行。

The with block is a context manager, it makes sure to close the file when the block ends, even if there is an exception. with块是上下文管理器,它确保在块结束时关闭文件,即使有异常也是如此。

If I understood question correctly: 如果我正确理解问题:

test.txt 的test.txt

fsdfj ljkjl
sdfsdf ljkkk
some ldfff
fffl lll
ppppp

script: 脚本:

chaine = 'some'

with open("test.txt", "r") as f:
    text = f.read()
    i = text.find(chaine)
    print(text[i:])

output: 输出:

some ldfff
fffl lll
ppppp

You can try like this, 你可以这样尝试

>>> with open('Service.txt', 'r') as f:
...     val = f.read()
>>> if "cheine" in val:
... # do something
with open("Service.txt", "r") as fichier:
    for ligne in fichier.readlines():
      if 'Call' in ligne:
      #What do I do 

Try this. 尝试这个。

Thank you all. 谢谢你们。

This is a file (Service.txt) while, I use to recover a text with it. 这是一个文件(Service.txt),而我使用它来恢复文本。

A text is only: 文本仅是:

     Supplementary service  =  Call forwarding unconditional


                            =  Call waiting


                            =  Calling line identification presentation

Service.txt Service.txt

Thank you. 谢谢。

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

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