从 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 制作的语音命令程序

原文由 Alok Naushad 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 646
2 个回答

只需使用字符串方法 .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('\"')

原文由 smci 发布,翻译遵循 CC BY-SA 4.0 许可协议

为此,您可以使用 eval()

 >>> url = "'http address'"
>>> eval(url)
'http address'

虽然 eval() 带来风险,但我认为在这种情况下它是安全的。

原文由 koliyat9811 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题