【问题标题】:Python Regular Expression from File来自文件的 Python 正则表达式
【发布时间】:2017-11-14 10:44:27
【问题描述】:

我想从文件中提取遵循某些序列的行。例如。一个文件包含很多行,我想按顺序排列

journey (a,b) from station south chennai to station punjab chandigarh
journey (c,d) from station jammu katra to city punjab chandigarh
journey (e) from station 

假设上面是代码,我想从前两行中提取以下信息:

例如,这是序列的第一个词是旅程—— 那么括号将包含两个单词,---- 然后来自---的话 然后它可能是词站或城市--- 然后是任何字符串 --- 然后再说一遍—— 然后它可以是词站或城市---

什么是正则表达式? 注意:括号中的单词可能包含特殊字符,例如 -,_

【问题讨论】:

  • 请编辑问题以显示示例数据和到目前为止您尝试过的代码。否则我怕你得不到任何帮助。
  • 你想要什么样的正则表达式?你打算用它来做什么:search 寻​​找这样的字符串,或 parse 看起来像这样的字符串(即将字符串拆分成(a, b, station, station, c, d))?
  • 我想首先搜索这种格式的完整行,因为其他序列中有许多其他行我只想要这个序列
  • 我忘了在我之前的评论中提问,但请向我们展示您解决此问题的尝试。这听起来像是一个相当简单的正则表达式。

标签: python regex


【解决方案1】:

这将返回你想要的元素:

import re

s = '''journey (a,b) from station south chennai to station punjab chandigarh
journey (c,d) from station jammu katra to city punjab chandigarh
journey (e) from station
journey (c,d) from station ANYSTRING jammu katra to ANYSTRING city punjab chandigarh
'''

matches_single = re.findall('journey (\([^,]+,[^,]+\)) from (\S+ \S+\s{0,1}\S*) to (\S+ \S+\s{0,1}\S*)', s)
for match in matches_single:
    print(match)
matches_line = re.findall('(journey \([^,]+,[^,]+\) from \S+ \S+\s{0,1}\S* to \S+ \S+\s{0,1}\S*)', s)
for match in matches_line:
    print(match)

【讨论】:

  • 嗨,它正在给 ('(a,b)', 'station south chennai', 'station punjab chandigarh') ('(c,d)', 'station jammu katra', 'city旁遮普昌迪加尔')不是从旅程开始的完整线路,还请告诉你如何定义车站或城市词应该在那里
  • 另外,如果我将线路旅程 (c,d) 从车站 jammu katra 字符串到城市旁遮普昌迪加尔,它不应该出现结果意味着在从车站 | 城市和到城市 | 之后应该有确切的两个词车站
  • 嗨,它正在给 ('(a,b)', 'station south chennai', 'station punjab chandigarh') ('(c,d)', 'station jammu katra', 'city punjab chandigarh')不是从旅程开始的完整线路,还请告诉你如何定义车站或城市词应该在那里,就像我给 > 它结果它不应该出现,因为我已将 > 放置在 station 或 city 的位置
  • 如果我总结一下> > > > punjab chandigarh>> > > 它应该给出前 4 行
  • 我现在还添加了一个选项来显示完整的行。您对您提出的问题非常不清楚。很难理解你想要什么。
猜你喜欢
  • 1970-01-01
  • 2022-10-24
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 1970-01-01
  • 2014-08-12
  • 1970-01-01
  • 2013-02-11
相关资源
最近更新 更多