问题
I'm looking for a way to search a text file for quotes made by author and then print them out. My script so far:
import re
#searches end of string
print re.search('"$', 'i am searching for quotes"')
#searches start of string
print re.search('^"' , '"i am searching for quotes"')
What I would like to do
import re
## load text file
quotelist = open('A.txt','r').read()
## search for strings contained with quotation marks
re.search ("-", quotelist)
## Store in list or Dict
Dict = quotelist
## Print quotes
print Dict
I also tried
import re
buffer = open('bbc.txt','r').read()
quotes = re.findall(r'.*"[^"].*".*', buffer)
for quote in quotes:
print quote
# Add quotes to list
l = []
for quote in quotes:
print quote
l.append(quote)
回答1:
Develop a regular expression that matches all the expected characters you would expect to see inside of a quoted string. Then use the python method findall
in re
to find all occurrences of the match.
import re
buffer = open('file.txt','r').read()
quotes = re.findall(r'"[^"]*"',buffer)
for quote in quotes:
print quote
Searching between " and ” requires a unicode-regex search such as:
quotes = re.findall(ur'"[^\u201d]*\u201d',buffer)
And for a document that uses " and ” interchangeably for quotation termination
quotes = re.findall(ur'"[^"^\u201d]*["\u201d]', buffer)
回答2:
You don't need regular expressions to find static strings. You should use this Python idiom for finding strings:
>>> haystack = 'this is the string to search!'
>>> needle = '!'
>>> if needle in haystack:
print 'Found', needle
Creating a list is easy enough -
>>> matches = []
Storing matches is easy too...
>>> matches.append('add this string to matches')
This should be enough to get you started. Good luck!
An addendum to address the comment below...
l = []
for quote in matches:
print quote
l.append(quote)
来源:https://stackoverflow.com/questions/10501959/search-for-quotes-with-regular-expression