简体   繁体   中英

Search for quotes with regular expression

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)

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM