[英]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. 然后在
re
使用python方法findall
查找所有匹配项。
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: 在“和”之间进行搜索需要unicode-regex搜索,例如:
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:
您应该使用以下Python惯用法来查找字符串:
>>> 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.