2016-12-03 143 views
12

刪除引號我有一個將使用谷歌STT引擎識別語音並給我回的結果的Python代碼,但我得到的字符串中的結果與「報價」。我不想在我的代碼中引用這些引號,因爲我會用它來運行許多命令,但它不起作用。我還沒有嘗試過任何東西,因爲我沒有得到任何東西嘗試! 這是Python代碼,將識別語音的功能:從字符串在Python

def recog(): 
    p = subprocess.Popen(['./speech-recog.sh'], stdout=subprocess.PIPE, 
              stderr=subprocess.PIPE) 
    global out,err 
    out, err = p.communicate() 
    print out 

這是speech-recog.sh:

#!/bin/bash 

hardware="plughw:1,0" 
duration="3" 
lang="en" 
hw_bool=0 
dur_bool=0 
lang_bool=0 
for var in "[email protected]" 
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 

這是由史蒂芬希克森的Voicecommand計劃採取樹莓派

+0

你是否要引用額外的引號來表示Python中的字符串?包括您擁有的命令和輸出,以及您特別想要的內容。 – ivan7707

+0

存在用於 「[蟒]刪除字符串引號」 – smci

回答

28

,如果他們始終出現就使用string .replace(),或.strip()如果他們只發生在開始和完成:

a = '"sajdkasjdsak" "asdasdasds"' 

a.replace('"', '') 
'sajdkasjdsak asdasdasds' 

# or, if they only occur at start and finish 
a.strip('\'') 
'sajdkasjdsak" "asdasdasds' 
1

您可以用空字符串替換「quote」字符,如下所示:

>>> a = '"sajdkasjdsak" "asdasdasds"' 
>>> a 
'"sajdkasjdsak" "asdasdasds"' 
>>> a = a.replace('"', '') 
>>> a 
'sajdkasjdsak asdasdasds' 

在你的情況,你可以爲out變量做同樣的。

1
if string.startswith('"'): 
    string = string[1:] 

if string.endswith('"'): 
    string = string[:-1] 
+3

的字符串方法'條(),lstrip(),rstrip()可以'是此許多重複。 – smci

+0

'lstrip()'從左邊刪除所有相同類型的字符。 '「‘’‘’hello'.lstrip(」「‘)=’hello''。這可能不是OP想要的東西。 –

+0

另外,你不覺得這種做法有點幼稚?如果有什麼行情,他希望除去在他的字符串中間您的解決方案將打破 –

2

有幾種方法可以完成此。

  • 您可以使用內置的字符串函數.replace()來代替報價的所有匹配給定的字符串:

    >>> s = '"abcd" efgh' 
    >>> s.replace('"', '') 
    'abcd efgh' 
    >>> 
    
  • 您可以使用字符串函數.join()和發電機表達刪除所有來自給定字符串的引號:

    >>> s = '"abcd" efgh' 
    >>> ''.join(c for c in s if c not in '"') 
    'abcd efgh' 
    >>> 
    
  • 您可以使用正則表達式從g iven字符串。這有讓你有時間和地點報價應刪除了控制額外的好處:

    >>> s = '"abcd" efgh' 
    >>> import re 
    >>> re.sub('"', '', s) 
    'abcd efgh' 
    >>>