使用正则表达式搜索报价 [英] 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"')
我想做什么
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
查找所有匹配项.
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
在和"之间进行搜索需要unicode-regex搜索,例如:
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)
这篇关于使用正则表达式搜索报价的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文