【发布时间】:2013-06-23 19:29:53
【问题描述】:
我想从文本文件中提取单引号之间的所有单词。文本文件如下所示:
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 for python 的某种组合来完成此操作。我尝试了以下方法:
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 出了什么问题?
谢谢!
--------------------------------
根据阿什维尼的评论:
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)
【问题讨论】:
-
阅读错误,这是 re.py 中的第 142 行,而不是您的文本文件。
-
我将编辑问题。感谢您指出这一点。