使用python从文本文件中查找和打印引号中的文本

时间:2013-01-30 19:32:34

标签: python quotation-marks

我是一个python初学者,希望python从文本文件中捕获引号中的所有文本。我尝试过以下方法:

filename = raw_input("Enter the full path of the file to be used: ")
input = open(filename, 'r')
import re
quotes = re.findall(ur'"[\^u201d]*["\u201d]', input)
print quotes

我收到错误:

Traceback (most recent call last):
  File "/Users/nithin/Documents/Python/Capture Quotes", line 5, in <module>
    quotes = re.findall(ur'"[\^u201d]*["\u201d]', input)
  File "/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

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

正如Bakuriu所指出的那样,你需要像这样添加.read()

quotes = re.findall(ur'[^\u201d]*[\u201d]', input.read())

open()只返回一个文件对象,而f.read()将返回一个字符串。另外,我猜你是想在引号之前得到两个引号之间的所有内容,而不只是[\^u201d]的零个或多个出现。所以我会尝试这个:

quotes = re.findall(ur'[\u201d][^\u201d]*[\u201d]', input.read(), re.U)

re.U说明了unicode。或者(如果你没有两组右双引号并且不需要unicode):

quotes = re.findall(r'"[^"]*"', input.read(), re.U)

最后,您可能希望选择与input不同的变量,因为input是python中的关键字。

您的结果可能如下所示:

>>> input2 = """
cfrhubecf "ehukl wehunkl echnk
wehukb ewni; wejio;"
"werulih"
"""
>>> quotes = re.findall(r'"[^"]*"', input2, re.U)
>>> print quotes
['"ehukl wehunkl echnk\nwehukb ewni; wejio;"', '"werulih"']

答案 1 :(得分:0)

您可以尝试使用某些python内置函数,而不是使用正则表达式。我会让你努力工作:

message = '''
"some text in quotes", some text not in quotes. Some more text 'In different kinds of quotes'.
'''
list_of_single_quote_items = message.split("'")
list_of_double_quote_items = message.split(""")

具有挑战性的部分将解释您的拆分列表的含义并处理所有边缘条件(字符串,转义序列等中只有一个引号)

相关问题