【问题标题】:Python program to extract text from a text file?Python程序从文本文件中提取文本?
【发布时间】:2014-05-31 09:30:38
【问题描述】:

我有一个通过转换 .srt 文件获得的文本文件。内容如下:

1 0:0:1,65 --> 0:0:7,85 你好,我的名字是加雷斯,在这个 视频,我将讨论列表推导 2 0:0:7,85 --> 0:0:9,749 在 Python 中。

我只想要文本文件中的单词,这样输出是一个新的文本文件 op.txt,输出表示为:

你好 我的 姓名 是 加雷斯 和

等等。

这是我正在开发的程序:

import os, re
f= open("D:\captionsfile.txt",'r')
k=f.read()
g=str(k)
f.close()
w=re.search('[a-z][A-Z]\s',g)
fil=open('D:\op.txt','w+')
fil.append(w)
fil.close()

但是我得到的这个程序的输出是:

没有任何 没有任何 没有任何

【问题讨论】:

  • 您的正则表达式错误。我认为您需要更多练习。

标签: python regex python-2.7 pyscripter


【解决方案1】:

如果我们假设m 是一个单词并且是am 的缩写并且in.txt 是您的文本文件,您可以使用

import re

with open('in.txt') as intxt:
    data = intxt.read()

x = re.findall('[aA-zZ]+', data)
print(x)

会产生

['Hello', 'my', 'name', 'is', 'Gareth', 'and', 'in', 'this', 'video', 'I', 'm', 'going', 'to', 'talk', 'about', 'list', 'comprehensions', 'in', 'Python']

您现在可以将x 写入新文件:

with open('out.txt', 'w') as outtxt:
    outtxt.write('\n'.join(x))

得到

I'm

而不是

I
m

你可以使用re.findall('[aA-zZ\']+')

【讨论】:

  • m是什么时候变成一个词的?
  • @Padraic Cunningham 我不确定“I'm”是一个单词还是应该被视为两个单词,即“I”和“am”,其中“I'm”中的“m”是“am”的缩写。
  • 你的正则表达式不是必须是'[a-zA-Z]+'吗?
  • 好的,肯定是'[a-zA-Z]+'。如果你使用'[aA-zZ\']+',你有从A到z的所有ASCII字符,这意味着像'hell[]o'这样的词也会被匹配,因为'['和']'在'A'和'z'之间(如果你有看看 ascii 表)。
【解决方案2】:
with open("out.txt","a") as f1:
    with open("b.txt")  as f:
        for line in f:
            if not line[0].isdigit():
                for word in line.split():
                    f1.write(re.sub(r'[,.!]', "", word)) # replace any punctuation you don't want
                    f1.write("\n")

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2010-09-24
    相关资源
    最近更新 更多