【问题标题】:How to remove punctuation from a string and remember the position of it from the string如何从字符串中删除标点符号并记住它在字符串中的位置
【发布时间】:2016-05-22 11:40:37
【问题描述】:

您好,我一直在尝试创建一个程序,它获取一个字符串并删除所有标点符号和大写字母,然后该程序应将所有标点符号和大写字母重新插入到句子的来源处。

这是我目前得到的;

sentence = 'I am called bob. What is your name?'
punc = ('!', '"', '£', '$', '%', '^', '&', '*', '(', ')', '¬', '`', '{', '}', '~', '@', ':', '?', '>', '<', ',', '.', '/', ';', '#', ']', '[', '/', '*')

Dictionary = {}
count = 0

for i in sentence:
    count = count + 1
    if i == punc:
        Dictionary[i] = count 

print(Dictionary)

我知道这不是很多,它什么也没做(我不知道为什么),但任何帮助将不胜感激。

我正在使用 python 3.4

【问题讨论】:

  • 拿一根绳子,用它做任何事,然后把那根绳子扔掉,重新使用原来的那根?为什么删除后要重新插入?
  • 这对学校来说是一项愚蠢的任务

标签: string python-3.x if-statement for-loop dictionary


【解决方案1】:

字符串是不可变的,因此没有插入或删除方法。但是,您可以将其更改为一个肯定是可变的列表。我可能会有一本以标点符号作为键的字典和每个索引的列表。您可能会遇到的问题是,如果您有多个标点符号,则无法保证它们会以正确的顺序插入。例如:

sentence = 'I am called bob. What is your name?'
punc = ('!', '"', '£', '$', '%', '^', '&', '*', '(', ')', '¬', '`', '{', '}', '~', '@', ':', '?', '>', '<', ',', '.', '/', ';', '#', ']', '[', '/', '*')

sentence = list(sentence)
Dictionary = {}

for i, p in enumerate(sentence): # enumerate() returns an iterable in (index, value) format
    if p in punc:
        if p in Dictionary:
            Dictionary[p].append(i)
        else:
            Dictionary[p] = [i]

print(Dictionary) # => {'?': [34], '.': [15]}

例如,如果我有一个带有随机数量的各种标点符号的奇怪格式的字符串:

sentence = 'I? am. cal?led ,bob. Wh,at. is your .name?.'
... # above code
print(sentence) # => "I? am. call?ed bob,. What .i,s your .name?."

这显然是不正确的。唯一可靠的方法是遍历 dict 从最低元素到最高元素并以这种方式添加它们。

最终代码:

original = sentence = 'I? am. cal?led ,bob. Wh,at. is your .name?.'
punc = ('!', '"', '£', '$', '%', '^', '&', '*', '(', ')', '¬', '`', '{', '}', '~', '@', ':', '?', '>', '<', ',', '.', '/', ';', '#', ']', '[', '/', '*')

sentence = list(sentence)
Dictionary = {}
seq = [] # list of all indices with any punctuation 

for i, p in enumerate(sentence):
    if p in punc:
        seq.append(i)
        if p in Dictionary:
            Dictionary[p].append(i)
        else:
            Dictionary[p] = [i]

sentence = list(filter(lambda x: x not in punc, sentence))
for i in seq:
    for key, indices in Dictionary.items():
        if i in indices:
            sentence.insert(i, key)
            indices.remove(i)
assert(''.join(sentence) == original)

【讨论】:

  • 谢谢,这正是我所需要的。
  • 我如何取出标点符号和大写字母并重新插入它们
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
相关资源
最近更新 更多