【问题标题】:How to extract text part from file using Python & Regular Expressions如何使用 Python 和正则表达式从文件中提取文本部分
【发布时间】:2019-09-13 15:10:53
【问题描述】:

使用 Python 我想读取一个文本文件,搜索一个字符串并打印此匹配字符串与另一个字符串之间的所有行。

文本文件如下所示:

Text=variables.Job_SalesDispatch.CaptionNew
    Tab=0
    TabAlign=0
    }
   }
  }
[UserVariables]
 User1=@StJid;IF(fields.Fieldtype="Artikel.Gerät"  , STR$(fields.id,0,0)  , @StJid)
[Parameters]
 [@Parameters]
  {
  [Parameters]
   {
   LL.ProjectDescription=? (default)
   LL.SortOrderID=
   }
  }
[PageLayouts]
 [@PageLayouts]
  {
  [PageLayouts]
   {
   [PageLayout]
    {
    DisplayName=
    Condition=Page() = 1
    SourceTray=0

现在我想打印所有“UserVariables”,所以只有[UserVariables] 和以方括号开头的下一行之间的行。在此示例中,这将是 [Parameters]

到目前为止我所做的是:

with open("path/testfile.lst", encoding="utf8", errors="ignore") as file:

  for line in file:
    uservars = re.findall('\b(\w*UserVariables\w*)\b', line)
    print (uservars)

什么只给了我[]

【问题讨论】:

  • 你想要的输出是什么?
  • 我想要的输出是User1=@StJid;IF(fields.Fieldtype="Artikel.Gerät" , STR$(fields.id,0,0) , @StJid)在这个例子中。但也可以有更多的 UserVariables,如 User2=@StJid;IF(fields.Fieldtype="Artikel.Referenzgerät" , STR$(fields.id,0,0) , @StJid)

标签: python regex file parsing


【解决方案1】:

我们可以尝试将re.findall 与以下正则表达式模式一起使用:

\[UserVariables\]\n((?:(?!\[.*?\]).)*)

这表示匹配[UserVariables] 标签,后跟一个看起来有点复杂的表达式:

((?:(?!\[.*?\]).)*)

这个表达式是一个 tempered dot 技巧,它匹配任何字符,一次一个,只要紧接在前面的是不是包含在方括号中的另一个标记。

matches = re.findall(r'\[UserVariables\]\n((?:(?!\[.*?\]).)*)', input, re.DOTALL)
print(matches)

[' User1=@StJid;IF(fields.Fieldtype="Artikel.Ger\xc3\xa4t"  , STR$(fields.id,0,0)  , @StJid)\n']

编辑:

我的回答假设整个文件内容位于内存中,在单个 Python 字符串中。您可以使用以下方式阅读整个文件:

with open('Path/to/your/file.txt', 'r') as content_file:
    input = content_file.read()
matches = re.findall(r'\[UserVariables\]\n((?:(?!\[.*?\]).)*)', input, re.DOTALL)
print(matches)

【讨论】:

  • RegEx 部分非常酷,正是我想要的。不幸的是,我太垃圾了,无法让它在我的代码中工作。
  • @Gardinero 查看我的更新。我的答案只有在您将整个文件内容读入单个 Python 字符串时才有效。假设您的内存要求/限制允许这样做,我的答案应该有效,并且基本上是单行的。
【解决方案2】:

如果使用正则表达式不是您的强制性要求,您可以使用以下内容:

with open("path/testfile.lst", encoding="utf8", errors="ignore") as file:
  inside_uservars = False
  for line in file:
    if inside_uservars:
      if line.strip().startswith('['):
        inside_uservars = False
      else:
        print(line)
    if line.strip() == '[UserVariables]':
      inside_uservars = True

【讨论】:

  • 谢谢。那个正在为我工​​作。我将通过代码学习一些东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-22
  • 2015-04-19
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
相关资源
最近更新 更多