问题是:
写一个脚本,读一个文件,把它分成几个句子,然后一个接一个地在屏幕上打印句子。不要使用为你做句子分裂的库。
以下是我的代码:
import re
fr=open('input.txt')
text=fr.read().strip()
fr.close()
Ms=re.finditer(' +([A-Z].+?\.) ',text)
for i in Ms:
print i.group(1)结果显示什么也没有。实际上,我知道可能出了什么问题,因为文件的第一句没有多个空格,但我不知道如何修复它。
以下是我的意见:
二甲双胍在6-8周内完全有效。它有三个主要影响(action)。
首先,它(经常)减少你的肝脏产生的血糖量,这大概会减少你的基本需求,帮助你的禁食次数。
其次,二甲双胍增加胰岛素,信号导致胰岛素敏感性增加:http://care.diabetesjournals.org/content/27/1/281.full。影响主要是在你的肌肉质量在你的身体。胰岛素抵抗也会影响其他各种物质,但胰岛素的最大利用是肌肉对葡萄糖的摄取。
第三,二甲双胍降低了digestion.It期间葡萄糖的吸收,我认为这是引起胃问题的原因之一。
发布于 2016-02-27 00:19:52
假设文件input.txt具有以下内容:
二甲双胍在6-8周内完全有效。它有三个主要影响(action)。 首先,它(经常)减少你的肝脏产生的血糖量,这大概会减少你的基本需求,帮助你的禁食次数。 其次,二甲双胍增加胰岛素,信号导致胰岛素敏感性增加:http://care.diabetesjournals.org/content/27/1/281.full。影响主要是在你的肌肉质量在你的身体。胰岛素抵抗也会影响其他各种物质,但胰岛素的最大利用是肌肉对葡萄糖的摄取。 第三,二甲双胍降低了digestion.It期间葡萄糖的吸收,我认为这是引起胃问题的原因之一。
以下是代码:
import re
with open('input.txt','r') as f: fin = f.read()
print re.sub('\.\s+', '.\n', fin)输出:
Metformin will reach full effectiveness in 6-8 weeks.
It has three primary effects (http://en.wikipedia.org/wiki/Metformin#Mechanism4of_action).
First, it (frequently) reduces the amount of blood sugar produced by your liver, this presumably will decrease your basal needs and help your fasting numbers.
Second, metformin increases the insulin, signaling resulting in increased insulin sensitivity: http://care.diabetesjournals.org/content/27/1/281.full.
The effect is primarily on the muscle mass in your body.
Insulin resistance also affects all kinds of other stuff, but the biggest utilization of insulin is in the uptake of glucose to muscles.
Third, Metformin decreases the absorption of glucose during digestion.It is this effect that I believe causes some of the gastric issues.由于格式不佳(两个句子之间缺少一个空格),其中一个句子不能正确地解析,因此应该在文本文件中进行修改。
UPDATE,尽管如此,请在文本文件不变的情况下尝试以下操作:
import re
with open('input.txt','r') as f: fin = f.read()
print re.sub('\.\s*([A-Z])', '.\n\g<1>', fin)发布于 2016-02-26 22:05:01
很难在没有看到您的输入的情况下进行评论,但是请注意,您需要小心引导和尾随空格。在下面的例子中,第一个单词被忽略了,因为它没有前导空间,如果您需要一个尾随空间,那么第二句话就会被忽略。
>>> text = "See Spot run. Run, Spot, run."
>>> re.findall(' +([A-Z].+?\.)',text)
['Spot run.',' Run, Spot, run.']
>>> re.findall(' +([A-Z].+?\.) ',text)
['Spot run. ']对于字符类,我们可以做得稍微好一点,但是您需要确定句子是如何划分的。
>>> re.findall('([\w, ]+\.)',text)
['See Spot run.', ' Run, Spot, run.']
>>> re.findall('[^.]+\.',text)
['See Spot run.', ' Run, Spot, run.']但是,在许多情况下,在句点上拆分将失败,例如示例输入中的URL,或如下所示:
>>> re.findall('[^.]+\.',"See Dr. Spock run. Run, Spock, run.")
['See Dr.', ' Spock run.', ' Run, Spock, run.']发布于 2016-02-26 21:45:46
试试这个:
import re
with open('input.txt', 'r') as f:
data = f.read()
print('\n'.join(re.split(r'\n', data, re.M)))https://stackoverflow.com/questions/35662258
复制相似问题