文本清理python代码

时间:2016-12-10 08:13:32

标签: python string-parsing data-cleaning

我的问题是不同的,因为答案传达了更深层次的问题,即简洁的代码与像森林一样的变量。我相信我应该得到声誉点,指出简洁缩短的变量代码的清晰度是为了找到逻辑问题。

我正在开发Dataquest教程数据Python btw 的好站点,并且遇到此字符串清理代码的问题。清理过的字符串与原始字符串完全一致,没有解析出来。

这里是代码,我尽量使其尽可能简洁:

ss = open('story.txt', 'r').read()
cc = [",", ".", ";", "\n", "'"]

print(ss + "\n\n\n")

cleaned_story = ""
def clean_text(x, y):
    cs = x
    for e in y:
        cs.replace(e, "")
    cs = cs.lower()
    return cs

cleaned_story = clean_text(ss, cc)
print(cleaned_story)
print(type(cleaned_story)) #this is just for weird test

2 个答案:

答案 0 :(得分:0)

没关系。我发现了这个问题。使代码更简洁帮助我立即看到错误。在使用replace方法后,我忘了将<div id="assistenzen"> <form> <select v-model="assistenz" multiple> <option v-for="option in options" v-bind:value="option"> {{ option.text }} </option> </select> <ul> <li v-for="assi in assistenz">{{assi.text}} <input v-model="assi.prozent"> {{assi.prozent}} </li> </ul> </form> </div> <script> var assistenz = new Vue({ el: '#assistenzen', data: { assistenz: 'keine Assistenz', options: [ { text: 'One', value: 'A', prozent: '0' }, { text: 'Two', value: 'B', prozent: '0' }, { text: 'Three', value: 'C', prozent: '0' } ] }, }); assistenz.config.devtools = true </script> 变量赋给自己。

我非常喜欢Python!

感谢StackOverflow。你是上帝!

答案 1 :(得分:0)

看起来你正在调用函数.replace(),它返回字符串的修改版本,但没有为返回值赋值。我将行改为

cs = cs.replace(e, "")

它工作正常。

ss = "this text, it is... a test;"
cc = [",", ".", ";", "\n", "'"]

print(ss + "\n\n\n")

cleaned_story = ""
def clean_text(x, y):
    cs = x
    for e in y:
        cs = cs.replace(e, "")
    cs = cs.lower()
    return cs

cleaned_story = clean_text(ss, cc)
print(cleaned_story)
print(type(cleaned_story)) #this is just for weird test