【问题标题】:removing square brackets and commas but not the commas in the sentence删除方括号和逗号,但不删除句子中的逗号
【发布时间】:2016-12-12 20:03:30
【问题描述】:
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()

例子:你好,你今天在做什么?

我的程序会将单词重新创建到位置,因此文本文件上的输出将是 ['Hello,' 'what', 'are', 'you', 'doing', 'today?'] [1, 2,3,4,5,6]

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

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

谢谢

【问题讨论】:

标签: python string file


【解决方案1】:

试试这个:

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)

祝你好运。

【讨论】:

    猜你喜欢
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多