【问题标题】:how to search for a specific from and to keyword in a file and print the sentence in python如何在文件中搜索特定的 from 和 to 关键字并在 python 中打印句子
【发布时间】:2019-02-24 23:12:27
【问题描述】:

我正在尝试获取文件作为输入并搜索特殊字符。 我将 from 和 to 键作为输入。 如果 to 关键字在下一行,我应该打印直到找到 to 关键字。

for line in contents:

if line.startswith("*CHI: ") :

       line = line.strip("*")
       tokenize = line.split()
       p.token_filter(tokenize)

说我有一个文件:

       *CHI: (hi) new [/] friend [//] there [/-] [ bch] [ bch ] /[]/ [/=]
<new>
<there>.
%mod: hi there.
*CHI: <dude>
<there>
*CHI: &=sighs <and instead the> [//] and then the gira?e got it and gave it to the elephant . 
*CHI: <he> [/] <he> [/] he hold it .
*CHI: then [/-] the doctor give the [/] money to the man
*CHI: and (i)s then (.) the little (.) gira?e is crying because it (i)s sinking

通过使用上面的代码,我得到如下输出:

['new', '[/]', 'friend', '[//]', 'there', 'bch', '/[]/']
['dude', 'dude']
['and', 'and', 'instead', 'the', 'the', '[//]', 'and', 'then', 'the', 'gira?e', 'got', 'it', 'and', 'gave', 'it', 'to', 'the', 'elephant', '.']
['he', 'he', '[/]', 'he', 'he', '[/]', 'he', 'hold', 'it', '.']
['then', 'the', 'doctor', 'give', 'the', '[/]', 'money', 'to', 'the', 'man']
['and', 'then', '(.)', 'the', 'little', '(.)', 'gira?e', 'is', 'crying', 'because', 'it', 'sinking']

我的另一个目标是我应该打印 ['new', '[/]', 'friend', '[//]', 'there', 'bch', '/[]/' 'new' 'there' '.'强>]

【问题讨论】:

  • "但我无法打印 "new" 和 "there"" ....这些行不是以 * 开头的,所以你的第一个 if 语句返回 False跨度>
  • 你想打印每一行吗?不知道目标是什么
  • @SuperStew OP 可能希望获取两个 *s 之间的所有内容。
  • 你在追求类似this 的东西吗?
  • 正则表达式答案可能是最好的方法

标签: python regex file search


【解决方案1】:

对于任意文本,您可以使用正则表达式:

>>> import re
>>> text = "*foo* bar *foobar*"
>>> re.findall("\*[^/*]*\*", text)
['*foo*', '*foobar*']

去掉星号:

>>> [s.replace("*", "") for s in re.findall("\*[^/*]*\*", text)]
['foo', 'foobar']

【讨论】:

  • 或者只是将[^/*]* 包装在一个捕获组中?顺便说一下,无需在字符集中转义*。你的斜线也是错误的。
  • 谁能单独解释一下(“*[^/*]**”, text)这部分
【解决方案2】:

如果您可以读取文件并将其转换为字符串。 我们可以使用

string = "123123STRINGabcabc"

def find_between( string, first, last ):
    try:
        start = string.index( first ) + len( first )
        end = string.index( last, start )
        return string[start:end]
    except ValueError:
        return ""

print find_between( string, "123", "abc" )

给予

123STRING

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多