使用正则表达式搜索引号

2024-06-16 11:45:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

Tags: ofinimportreforsearchstringsearching
2条回答

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

import re

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

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

在“和”之间搜索需要unicode正则表达式搜索,例如:

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)

相关问题 更多 >