0

我正在寻找一种方法来搜索文本文件以查找作者引用的内容,然后将其打印出来。到目前为止我的脚本:

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)
4

2 回答 2

4

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

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)
于 2012-05-08T15:58:25.370 回答
-3

您不需要正则表达式来查找静态字符串。您应该使用这个 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)
于 2012-05-08T15:56:31.953 回答