【问题标题】:Need regex to extract characters from python dictionary需要正则表达式从python字典中提取字符
【发布时间】:2017-04-22 15:10:20
【问题描述】:

我有一本字典,可以像这样打印出data['longitude']data['latitude']

(91°38'28.2"E)(22°40'34.3"N)
(92°04´14.1´´E)(21°37´00.8´´N)
(E-092° 15. 715')(N-20° 56.062')
(91°49'10.63"E)(24°20'05.40"N)
(91°26'31.92"E)(24°07'35.15"N)
(90°08'15.07"E)(24°41'14.71"N)
(90°04'7.97"E)(24°42'29.34"N)
(90°04'10.06"E)(24°42'32.8"N)
(E-092° 15.776')(N-20° 56.065')
(91°46'26.90"E)(24°18'47.16"N)
(E-092° 15.649')(N-20° 56.023')
(91°46'26.90"E)(24°18'47.16"N)
(91°49'08.08"E)(24°20'06.33"N)
(92° 2'31.25"E)(21°20'58.79"N)
(E-092° 15.776')(N-20° 56.065')
(E-092° 15. 486')(N-20° 56.022')

我要将这些数字转换为十进制度。例如,

92° 2'31.25"E -> (92 + (2/60) + (31.25/3600)) -> 92.042
20° 56.023' -> 20 + (56.023/60) -> 20.993

典型的 python 字符拆分无法工作,因为数字的模式不一致。

(data['longitude'][:3]) + (data['longitude'][5:2]/60) + (data['longitude'][8:5]/3600) 

我使用this thread 从 docx 文件中提取这些值。现在我又被困住了。

【问题讨论】:

  • 你的输入是什么,元组列表还是字符串列表?
  • 您是否尝试过使用在线正则表达式测试器?喜欢 regex101.com?
  • Unicode 还是 ascii?
  • 我的输入是 unicode 字符串 - @RomanPerekhrest。我仍在使用正则表达式代码。 (N-(.{,12})([0-9]|\')|[0-9].{,12}N)[;, ]+(E-(.{,12})([0-9]|\')|[0-9].{,12}E)。它需要先搜索90-92和20-24度范围,或者搜索分钟和秒然后得出度数。

标签: python regex dictionary


【解决方案1】:

你可以去(见a demo on regex101.com):

import re

coordinates = """
(91°38'28.2"E)(22°40'34.3"N)
(92°04´14.1´´E)(21°37´00.8´´N)
(E-092° 15. 715')(N-20° 56.062')
(91°49'10.63"E)(24°20'05.40"N)
(91°26'31.92"E)(24°07'35.15"N)
(90°08'15.07"E)(24°41'14.71"N)
(90°04'7.97"E)(24°42'29.34"N)
(90°04'10.06"E)(24°42'32.8"N)
(E-092° 15.776')(N-20° 56.065')
(91°46'26.90"E)(24°18'47.16"N)
(E-092° 15.649')(N-20° 56.023')
(91°46'26.90"E)(24°18'47.16"N)
(91°49'08.08"E)(24°20'06.33"N)
(92° 2'31.25"E)(21°20'58.79"N)
(E-092° 15.776')(N-20° 56.065')
(E-092° 15. 486')(N-20° 56.022')
"""

rx = re.compile(r"(?P<degree>-?\d+)°\s*(?P<minute>[^'´]+)'")

def convert(match):
    try:
        degree = float(match.group('degree'))
        minute = float(match.group('degree'))
        result = degree + minute/60
    except:
        result = -1
    finally:
        return result

coordinates_new = [convert(match) for match in rx.finditer(coordinates)]
print(coordinates_new)

【讨论】:

  • 谢谢@Jan。我最终使用了这个表达式 - ((?P&lt;degree&gt;\d+)°\s*(?P&lt;minute&gt;[^\'´]+)[\'´]?\b(?P&lt;second&gt;[^\"´´]+))。我也需要转换秒数。我认为您需要在minute = float(match.group('degree')) 内将degree 更改为minute
猜你喜欢
  • 1970-01-01
  • 2012-12-19
  • 1970-01-01
  • 1970-01-01
  • 2023-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
相关资源
最近更新 更多