使用python从文本文件中提取单词

时间:2013-06-26 15:06:18

标签: python regex text nltk

我想从文本文件中提取单引号之间的所有单词。文本文件如下所示:

u'MMA': 10,
=u'acrylic'= : 19,
== u'acting lessons': 2,
=u'aerobic': 141,
=u'alto': 2= 4,
=u&#= 39;art therapy': 4,
=u'ballet': 939,
=u'ballroom'= ;: 234,
= =u'banjo': 38,

理想情况下,我的输出看起来像这样:

MMA,
acrylic,
acting lessons,
...

从浏览帖子来看,似乎我应该使用一些NLTK / regex的组合来实现这一目标。我尝试过以下方法:

import re

file = open('artsplus_categories.txt', 'r').readlines()

for line in file:
    list = re.search('^''$', file)

file.close()

并收到以下错误:

  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 142, in search
    return _compile(pattern, flags).search(string)
TypeError: expected string or buffer

我认为错误可能是由于我如何寻找模式造成的。我的逻辑是我在' ....'。

内搜索所有内容

绊倒re.py?

谢谢!

--------------------------------

遵循Ashwini的评论:

import re

file = open('artsplus_categories.txt', 'r').readlines()

for line in file:
    list = re.search('^''$', line)

print list

#file.close()

但输出中没有任何内容:

Samuel-Finegolds-MacBook-Pro:~ samuelfinegold$ /var/folders/jv/9_sy0bn10mbdft1bk9t14qz40000gn/T/Cleanup\ At\ Startup/artsplus_categories_clean-393952531.278.py.command ; exit;
None
logout


@Rasco:这是我得到的错误:

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/re.py", line 177, in findall
    return _compile(pattern, flags).findall(string)
TypeError: expected string or buffer
logout

我正在使用此代码:

file2 = open('artsplus_categories.txt', 'r').readlines()
list = re.findall("'[^']*'", file2)
for x in list:
    print (x)

2 个答案:

答案 0 :(得分:2)

您没有将line传递给正则表达式,而是将整个列表(文件)传递给它。您应该将line传递给re.search而不是file

for line in file:
    lis = re.search('^''$', line) # line not file

请勿使用listfile作为变量名称。它们是内置函数。

<强>更新

with open('artsplus_categories.txt') as f:
    for line in f:
        print re.search(r"'(.*)'", line).group(1)
...         
MMA
acrylic
acting lessons
aerobic
alto
art therapy
ballet
ballroom
banjo

答案 1 :(得分:2)

试试这个代码示例:

import re

file =  """u'MMA': 10,
        =u'acrylic'= : 19,
        == u'acting lessons': 2,
        =u'aerobic': 141,
        =u'alto': 2= 4,
        =u&#= 39;art therapy': 4,
        =u'ballet': 939,
        =u'ballroom'= ;: 234,
        = =u'banjo': 38,"""

list = re.findall("'[^']*'", file)
for x in list:
    print (x)

显示正确的值。请记住,示例中的某个值无法正确打开引号,因此匹配将在那里打破。