从 Python 中的字符串中删除引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40950791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:15:00  来源:igfitidea点击:

Remove quotes from String in Python

pythonstringspeech-recognitiongoogle-voice

提问by Alok Naushad

I have a python Code that will recognize speech using the Google STT engine and give me back the results but I get the results in strings with "quotes". I don't want that quotes in my code as I will use it to run many commands and it doesn't work. I haven't tried anything so far as I didn't get anything to try! This is the function in the python code that will recognize speech:

我有一个 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

This is speech-recog.sh:

这是语音识别.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 }' | awk -F"," '{print }' | tr -d '\n'

rm /dev/shm/out.flac

This was taken from Steven Hickson's Voicecommand Program made for Raspberry Pi

这取自 Steven Hickson 为 Raspberry Pi 制作的语音命令程序

回答by smci

Just use string methods .replace()if they occur throughout, or .strip()if they only occur at the start and/or finish:

.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('\"')

回答by koliyat9811

You can use eval() for this purpose

为此,您可以使用 eval()

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

while eval() poses risk , i think in this context it is safe.

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

回答by Christian Dean

There are several ways this can be accomplished.

有几种方法可以实现这一点。

  • You can make use of the builtin string function .replace()to replace all occurrences of quotes in a given string:

    >>> s = '"abcd" efgh'
    >>> s.replace('"', '')
    'abcd efgh'
    >>> 
    
  • You can use the string function .join()and a generator expression to remove all quotes from a given string:

    >>> s = '"abcd" efgh'
    >>> ''.join(c for c in s if c not in '"')
    'abcd efgh'
    >>> 
    
  • You can use a regular expression to remove all quotes from given string. This has the added advantage of letting you have control over when and where a quote should be deleted:

    >>> s = '"abcd" efgh'
    >>> import re
    >>> re.sub('"', '', s)
    'abcd efgh'
    >>> 
    
  • 您可以使用内置字符串函数.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'
    >>> 
    

回答by Harald Nordgren

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

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

回答by Aza Tulepbergenov

You can replace "quote" characters with an empty string, like this:

您可以用空字符串替换“引用”字符,如下所示:

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

In your case, you can do the same for outvariable.

在您的情况下,您可以对out变量执行相同的操作。

回答by dldnh

to return the innards of optional quotes

返回可选引号的内部结构

re.sub('''^(['"])(.*?)\1$''', '\2', str)
       ^^^                ^^^ (triple quotes so you can use ' & " inside)
          ^              ^    (match start/end of string)
           ^    ^             (group 1)
            ^^^^              (group 1 is an optional single or double quote)
                 ^   ^        (group 2)
                  ^^^         (group 2 is anything - non-greedy)
                      ^^^     (then match whatever group 1 is)

if there is a single or double quote at the beginning, that goes into group 1. if there isn't, empty goes into group 1. then, anything at all goes into group 2, but it's non-greedy, so it will stop if it finds what follows, which happens to be a match of group 1. and that has to be at the end of the string.

如果开头有单引号或双引号,则进入第 1 组。如果没有,则空进入第 1 组。然后,任何东西都进入第 2 组,但它是非贪婪的,因此它会停止如果它找到后面的内容,这恰好是第 1 组的匹配项,并且必须位于字符串的末尾。

since we put the stuff between the quotes in group 2, we use that as the replacement.

由于我们将内容放在第 2 组中的引号之间,因此我们将其用作替换。

and voila the quotes are gone.

瞧,引号不见了。