【问题标题】:Find string in file and copy until a specific character appears in Python在文件中查找字符串并复制,直到特定字符出现在 Python 中
【发布时间】:2019-02-11 10:17:31
【问题描述】:

我有多个 .txt 文件,其中的信息在转换后如下所示:

    >  **   ** **|** **     STYLE #        ** **|** **   DESCR  :  Potrero415;Tbl-
Rnd                 ** **\--------** **         ** **\--** **ZONE  1** **\--**
**           ** **\--** **ZONE  2** **\--** **      ** **\----** **      -T1-
-T2-  -T3-


                ** 

我想获取从 DESCR: 到下一行开始的所有内容 ** **\--** ** ZONE 2 ** 所以我的字符串应该是这样的:DESCR : Potrero415;Tbl-Rnd 请注意,在此特定部分之前的文件中有多行文本,并且 DESCR 一词仅出现在我要复制的位置,之前没有其他出现。

我知道在** **\出现之前可以使用split 所有文件格式相同,只需从DESCR:** **查找即可

我知道我冒着在这篇文章上投反对票的风险。 更新: 我设法找到了这个词的外观:

lines = test.readlines()
test.close()
for line in lines:
    line = line.strip()
    if line.find("DESCR") != -1:
        print("FOUND")

test 是我打开的文件

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 立即更新:)
  • “转换后”,什么样的转换?
  • 使用 html2text 从 .htm 到 .txt
  • 你说可以用split,那你为什么不用呢?

标签: python string file


【解决方案1】:

你可以使用正则表达式

import re

match = re.search('(?=DESCR).*?(?=\*\*)', your_txt)
print(match.group(0))

会输出:

DESCR : Potrero415;Tbl-Rnd

Regex Demo with your test string

地点:

Positive Lookahead (?=DESCR)
Assert that the Regex below matches
DESCR matches the characters DESCR literally (case sensitive)
.*? matches any character 
*? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy)
Positive Lookahead (?=\*\*)
Assert that the Regex below matches
\* matches the character * literally (case sensitive)
\* matches the character * literally (case sensitive)
Global pattern flags
s modifier: single line. Dot matches newline characters  

【讨论】:

  • 解释得很清楚,谢谢您的宝贵时间!
【解决方案2】:

听起来像是正则表达式的工作。

s 是您文件的内容。

>>> import re
>>> s = '''    >  **   ** **|** **     STYLE #        ** **|** **   DESCR  :  Potrero415;Tbl-
... Rnd                 ** **\--------** **         ** **\--** **ZONE  1** **\--**
... **           ** **\--** **ZONE  2** **\--** **      ** **\----** **      -T1-
... -T2-  -T3-
... 
... 
...                 ** '''
>>> 
>>> re.search('(DESCR\s*:.*?)\s*\*\* \*\*', s, re.DOTALL).group(1)
'DESCR  :  Potrero415;Tbl-\nRnd'

Demo on regex101

(在正则表达式之前加上 (?s) 与提供 re.DOTALL 参数的效果相同。)

【讨论】:

  • 谢谢!祝你有美好的一天:)
猜你喜欢
  • 1970-01-01
  • 2012-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多