簡體   English   中英

Python在引號之間找到文件中的文本

[英]Python find text in file between quotation marks

我試圖將引號內的文本捕獲並將其設置為變量,以供以后更改。 我知道如何在bash shell中執行此操作,但是我不知如何在Python中執行此操作。

我從此開始,但我希望有人可以指出我的錯誤所在。

import re
input = open(filename, 'r')
quotes = re.findall(r'"[^"]*"', input.read(), re.U)
print quotes

可悲的是,它輸出:

['"test1"', '"test2"']

在尋找的時候:

value1 = test1
value2 = test2

在Bash中,我使用了它(但是我顯然不能這樣使用!):

i=0
regex='"([^"]*)"'
while read line
do
    if [[ $line =~ $regex ]]; then
        printf -v "text$i" '%s' "${BASH_REMATCH[1]}"
        i=$((i + 1))
    fi
done < filename

echo "value1: $text0"
echo "value2: $text1"

使用一個非捕獲組(?:...) ,如下所示:

In [18]: re.findall('(?:")([^"]*)(?:")', '''hello "foo" "bar" haha''')
Out[18]: ['foo', 'bar']

或使用非消費組(?<=...)等:

In [14]: re.findall('(?<=")[^"]*(?=")', '''hello "foo" "bar" haha''')
Out[14]: ['foo', ' ', 'bar']

后者有一個副作用,即在"foo""bar"之間也選擇" " "bar"

這里的問題是兩個字符串( " " )之間的正則表達式匹配。
使用以下內容:

vars = re.findall('"(.*?)"', text)

我在python中使用的正則表達式與bash中的正則表達式不同。它應與“([[^“] *)”一起使用。

import re
input = open(filename, 'r')
quotes = re.findall(r'"([^"]*)"', input.read(), re.U)
for value in quotes :
    print value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM