繁体   English   中英

使用正则表达式搜索报价

[英]Search for quotes with regular expression

我正在寻找一种方法来搜索文本文件中作者的报价,然后打印出来。 到目前为止,我的脚本是:

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)

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

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)

您不需要正则表达式来查找静态字符串。 您应该使用以下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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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