使用正则表达式搜索引号

时间:2012-05-08 15:46:05

标签: python regex quotation-marks

我正在寻找一种方法来搜索文本文件以获取作者所做的报价,然后将其打印出来。到目前为止我的脚本:

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"')

我想做什么

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

我也试过

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)

2 个答案:

答案 0 :(得分:2)

开发一个正则表达式,匹配您希望在带引号的字符串中看到的所有预期字符。然后使用findall中的python方法re查找匹配的所有匹配项。

import re

buffer = open('file.txt','r').read()

quotes = re.findall(r'"[^"]*"',buffer)
for quote in quotes:
  print quote

在“和”之间搜索需要unicode-regex搜索,例如:

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

对于使用“和”可互换的报价终止

的文件
quotes = re.findall(ur'"[^"^\u201d]*["\u201d]', buffer)

答案 1 :(得分:-2)

您不需要正则表达式来查找静态字符串。您应该使用此Python习惯用于查找字符串:

>>> haystack = 'this is the string to search!'
>>> needle = '!'
>>> if needle in haystack:
       print 'Found', needle

创建列表很简单 -

>>> matches = []

存储匹配也很容易......

>>> matches.append('add this string to matches')

这应该足以让你入门。祝你好运!

解决以下评论的附录......

l = []
for quote in matches:
    print quote
    l.append(quote)