[英]Remove quotes from String in Python
我有一個 python 代碼,它將使用 Google STT 引擎識別語音並將結果返回給我,但我得到的結果是帶有“引號”的字符串。 我不希望在我的代碼中使用引號,因為我將使用它來運行許多命令並且它不起作用。 我還沒有嘗試任何東西,因為我沒有嘗試任何東西! 這是python代碼中識別語音的函數:
def recog():
p = subprocess.Popen(['./speech-recog.sh'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
global out,err
out, err = p.communicate()
print out
這是語音識別.sh:
#!/bin/bash
hardware="plughw:1,0"
duration="3"
lang="en"
hw_bool=0
dur_bool=0
lang_bool=0
for var in "$@"
do
if [ "$var" == "-D" ] ; then
hw_bool=1
elif [ "$var" == "-d" ] ; then
dur_bool=1
elif [ "$var" == "-l" ] ; then
lang_bool=1
elif [ $hw_bool == 1 ] ; then
hw_bool=0
hardware="$var"
elif [ $dur_bool == 1 ] ; then
dur_bool=0
duration="$var"
elif [ $lang_bool == 1 ] ; then
lang_bool=0
lang="$var"
else
echo "Invalid option, valid options are -D for hardware and -d for duration"
fi
done
arecord -D $hardware -f S16_LE -t wav -d $duration -r 16000 | flac - -f --best --sample-rate 16000 -o /dev/shm/out.flac 1>/dev/shm/voice.log 2>/dev/shm/voice.log; curl -X POST --data-binary @/dev/shm/out.flac --user-agent 'Mozilla/5.0' --header 'Content-Type: audio/x-flac; rate=16000;' "https://www.google.com/speech-api/v2/recognize?output=json&lang=$lang&key=key&client=Mozilla/5.0" | sed -e 's/[{}]/''/g' | awk -F":" '{print $4}' | awk -F"," '{print $1}' | tr -d '\n'
rm /dev/shm/out.flac
這取自 Steven Hickson 為 Raspberry Pi 制作的語音命令程序
只需使用字符串方法.replace()
如果它們始終出現,或者.strip()
如果它們只出現在開始和/或結束處:
a = '"sajdkasjdsak" "asdasdasds"'
a = a.replace('"', '')
'sajdkasjdsak asdasdasds'
# or, if they only occur at start and end...
a = a.strip('\"')
'sajdkasjdsak" "asdasdasds'
# or, if they only occur at start...
a = a.lstrip('\"')
# or, if they only occur at end...
a = a.rstrip('\"')
為此,您可以使用 eval()
>>> url = "'http address'"
>>> eval(url)
'http address'
雖然 eval() 存在風險,但我認為在這種情況下它是安全的。
有幾種方法可以實現這一點。
您可以使用內置字符串函數.replace()
來替換給定字符串中所有出現的引號:
>>> s = '"abcd" efgh' >>> s.replace('"', '') 'abcd efgh' >>>
您可以使用字符串函數.join()
和生成器表達式從給定字符串中刪除所有引號:
>>> s = '"abcd" efgh' >>> ''.join(c for c in s if c not in '"') 'abcd efgh' >>>
您可以使用正則表達式從給定字符串中刪除所有引號。 這有一個額外的好處,讓您可以控制何時何地刪除引用:
>>> s = '"abcd" efgh' >>> import re >>> re.sub('"', '', s) 'abcd efgh' >>>
最簡單的方法是:
s = '"sajdkasjdsaasdasdasds"'
import json
s = json.loads(s)
if string.startswith('"'):
string = string[1:]
if string.endswith('"'):
string = string[:-1]
您可以用空字符串替換“引用”字符,如下所示:
>>> a = '"sajdkasjdsak" "asdasdasds"'
>>> a
'"sajdkasjdsak" "asdasdasds"'
>>> a = a.replace('"', '')
>>> a
'sajdkasjdsak asdasdasds'
在您的情況下,您可以對out
變量執行相同的操作。
添加到@Christian 的評論:
替換字符串中的所有單引號或雙引號:
s = "'asdfa sdfa'"
import re
re.sub("[\"\']", "", s)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.