首页 > 解决方案 > 如何将字符串中的“未定义”替换为 0?

问题描述

我目前正在用 Python 编写一个程序,它读取在 Praat 中生成的语音报告,提取每个变量的值并将其写入 csv 文件。我在 Python 中检查了包含语音报告的变量的类型,它似乎是字符串类型,正如预期的那样。但是,当我尝试使用以下方法将 --undefined-- 的实例替换为 '0' 时,它似乎不起作用?

voice_report_str.replace('undefined', '0')

谁能告诉我为什么这种方法不能按预期工作?

Praat 生成的语音报告:

Pitch:
   Median pitch: 124.541 Hz
   Mean pitch: 124.518 Hz
   Standard deviation: 5.444 Hz
   Minimum pitch: 119.826 Hz
   Maximum pitch: 132.017 Hz
Pulses:
   Number of pulses: 4
   Number of periods: 3
   Mean period: 8.269978E-3 seconds
   Standard deviation of period: 0.372608E-3 seconds
Voicing:
   Fraction of locally unvoiced frames: 94.000%   (94 / 100)
   Number of voice breaks: 0
   Degree of voice breaks: 0   (0 seconds / 0 seconds)
Jitter:
   Jitter (local): 4.210%
   Jitter (local, absolute): 348.203E-6 seconds
   Jitter (rap): 1.852%
   Jitter (ppq5): --undefined--
   Jitter (ddp): 5.556%
Shimmer:
   Shimmer (local): --undefined--
   Shimmer (local, dB): --undefined-- dB
   Shimmer (apq3): --undefined--
   Shimmer (apq5): --undefined--
   Shimmer (apq11): --undefined--
   Shimmer (dda): --undefined--
Harmonicity of the voiced parts only:
   Mean autocorrelation: 0.670552
   Mean noise-to-harmonics ratio: 0.514756
   Mean harmonics-to-noise ratio: 3.176 dB

我的代码

def measurePitch(voiceID, f0min, f0max, unit, startTime, endTime):
    sound = parselmouth.Sound(voiceID) # read the sound
    pitch = call(sound, "To Pitch", 0.0, f0min, f0max) #create a praat pitch object
    pulses = parselmouth.praat.call([sound, pitch], "To PointProcess (cc)")
    duration = parselmouth.praat.call(pitch, "Get end time")
    voice_report_str = parselmouth.praat.call([sound, pitch, pulses], "Voice report", startTime, endTime, 75, 600, 1.3, 1.6, 0.03, 0.45)
    voice_report_str.replace('undefined', '0')
    s=re.findall(r'-?\d+\.?\d*',voice_report_str)
    print(voice_report_str)
    print(len(s))
    report = [s[21], s[22]+'E'+s[23],s[24],s[26],s[27],s[28],s[29],s[31],s[33],s[35]]

    return report

标签: pythonstringreplaceundefined

解决方案


我看不到你的整个代码,但我假设你做了这样的事情:

text = "This is my text"
text.replace("my", "0") # nothing really happened, text is still the same
# text == "This is my text"

所以你应该这样做:

text = "This is my text"
text = text.replace("my", "0") # text is changed, yay
# text == "This is 0 text"

推荐阅读