删除方括号和逗号但不删除句子中的逗号

时间:2016-12-12 20:03:30

标签: python string file

sentence = input("Please enter a sentence:")

words = sentence.split()

position= [0]

for count, i in enumerate(words):

    if words.count(i) <2:

        position.append(max(position) +1)

    else:
        position.append(words.index(i) +1)

position.remove(0)

print (position)

words = str(words)

position = str(position)

file = open("list_and_positions_of_words.txt","w")

file.write (words +'\n') 

file.write(position)

file.close()

示例:您好,您今天在做什么?

我的程序会重新创建位置的单词,所以文本文件的输出将是['你好','什么','是','你','做','今天?'] [1, 2,3,4,5,6]

我现在需要做的是拿这个文件打开并阅读然后打印原始句子,包括大写字母和标点符号(这不会作为列表)。

有没有办法可以删除方括号和逗号,但不能删除句子中的逗号,只是将单词分隔为列表的逗号。

由于

1 个答案:

答案 0 :(得分:0)

试试这个:

file = "['Hello,', 'what', 'are', 'you', 'doing', 'today?'][1,2,3,4,5,6]"

start = ''.join(file).find('[') + 1
end = ''.join(file).find(']', start)
new_string = ''.join(file)[start:end]
original = new_string.rstrip("'").lstrip("'").replace("', '", " ")

print(original)
祝你好运。