【问题标题】:Splitting and saving parts of a input text分割和保存部分输入文本
【发布时间】:2021-06-13 19:23:15
【问题描述】:

我试图弄清楚如何根据不同的时期在 python 中将文本拆分并保存为不同的句子,例如, . ? !。但有些文本有小数点,re.split 认为这是一个句点。我想知道如何解决这个问题?任何帮助将不胜感激!

例如文字:

直径 0.75 英寸的钢制拉杆长 4.8 英尺,承载 13.5 基普的负载。求拉应力、总变形、单位应变和杆径的变化。

【问题讨论】:

标签: python split


【解决方案1】:

这将取决于您的输入,但如果您可以假设您想要拆分的任何时期都后跟一个空格,那么您可以简单地这样做:

>>> s = 'A 0.75-in-diameter steel tension rod is 4.8 ft long and carries a load of 13.5 kip. Find the tensile stress, the total deformation, the unit strains, and the change in the rod diameter.'
>>> s.split('. ')
['A 0.75-in-diameter steel tension rod is 4.8 ft long and carries a load of 13.5 kip', 'Find the tensile stress, the total deformation, the unit strains, and the change in the rod diameter.']

对于比这更复杂的事情,您可能希望使用这样的正则表达式:

import re
re.split(r'[\.!?]\s', s)

【讨论】:

  • 太酷了!谢谢。另外,如果我想对句子的另一端做同样的事情怎么办,比如?和 !。我想知道是否有一种方法可以在一个部分中这样做,还是我必须分别为每个部分做 s.split?
  • 您可能希望将正则表达式用于比我在答案中发布的内容更复杂的任何内容。我将编辑我的答案以包括为此使用正则表达式。
  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多