Python - 删除没有函数的空格和标点符号

时间:2013-11-18 13:06:11

标签: python function space punctuation

首先,抱歉我的英语不好。我是初学程序员,我的python程序有些问题。 我必须制作一个规范化空格和标点符号的程序,例如:

如果我输入一个名为

的字符串
"   hello   how,   are  u?   "

新字符串必须是......

"Hello how are u"

但是在我的代码中,结果看起来像这样,我不知道为什么:

 "helloo how,, aree u??"

注意:我不能使用任何类型的函数,如split(),strip()等...

这是我的代码:

from string import punctuation

print("Introduce your string: ")
string = input() + " "
word = ""
new_word = ""
final_string = ""

#This is the main code for the program
for i in range(0, len(string)):
    if (string[i] != " " and (string[i+1] != " " or string[i+1] != punctuation)):
        word += string[i]
    if (string[i] != " " and (string[i+1] == " " or string[i+1] == punctuation)):
        word += string[i] + " "
        new_word += word
        word = ""

#This destroys the last whitespace
for j in range(0,len(new_word)-1):
    final_string += new_word[j]

print(final_string)

谢谢大家。

修改

现在我有了这段代码:

letter = False

for element in my_string:
    if (element != " " and element != punctuation):
        letter= True
        word += element


print(word)

但现在,问题是我的程序无法识别标点,所以如果我把:

"Hello   ... how  are u?"

必须像"Hellohowareu"

但它就像:

"Hello...howareu?

3 个答案:

答案 0 :(得分:3)

我不会为你编写代码,因为这显然是功课,但我会给你一些提示。

我认为你检查下一个字符的方法有点容易出错。相反,当你看到空格或标点符号时,我会设置一个标志。下一次循环,检查标志是否已设置:如果是,并且您仍然看到空格,则忽略它,否则,将标志重置为false。

答案 1 :(得分:0)

好的,首先,你不需要遍历一个范围,python中的字符串是可迭代的。例如:

my_string = 'How are you?'

for char in my_string:
  #do something each character

其次,您正在使用一种非常不稳定的方法来处理您要删除的内容。看起来你的方法用于捕获字符后出现的空格会导致最后一个字符的双重追加。我会使用一种不同的方法,更多地集中在你所处的位置,而不是你面前的那些。

答案 2 :(得分:0)

现在这看起来很像家庭作业,所以这是我的流处理解决方案,如果你能向老师解释一下,我怀疑他们会介意你自己没有真正做到这一点

def filter(inp):
    for i in inp:
        yield " " if i in " ,.?!;:" else i

def expand(inp):
    for i in inp:
        yield None if i == " " else object(), i

def uniq(inp):
    last = object()
    for key, i in inp:
        if key == last:
            continue
        yield key, i

def compact(inp):
    for key, i in inp:
        yield i

normalised = compact(uniq(expand(filter(input()))))
相关问题