如何从列表中删除符号然后将其放回原处?



所以我必须制作一个从txt文件中读取的代码,然后将txt转换为列表来分析它(转换单位(。我想做的是从列表中删除特定单词的标点符号以对其进行分析,然后将其放在与以前相同的位置。此列表总是可以更改的,因为代码必须适用于我给出的每个 txt。

如何将符号准确地放回以前的位置?我不能为此使用任何软件包。

punct=['?', ':', ';', ',', '.', '!','"','/']
size = {'mm':1, 'cm':10, 'm':100, 'km':1000}
with open('random_text','r') as x:
    LIST=x.read().split() 
    for item in LIST:
        if item[:-1] in size.keys() and item[-1] in punct:
            punct_item=item
            non_punct_item=item[:-1]
            symbol=item[-1]

读取文件不会改变任何内容,因此,如果您读取文件一次并进行所需的所有修改(在这种情况下删除标点符号(。然后,当您再次需要标点符号时,只需再次重读文件,所有内容都应处于同一位置。

更快的方法是:

punct=['?', ':', ';', ',', '.', '!','"','/']
size = {'mm':1, 'cm':10, 'm':100, 'km':1000}
# Do all modifications you need 
words_temp = None
with open('file1.txt','r') as file:
    words = file.read().split() 
    words_temp = words
    for item in words:
        if item[:-1] in size.keys() and item[-1] in punct:
            punct_item=item
            non_punct_item=item[:-1]
            symbol=item[-1]
words = words_temp
del words_temp

这是更简单的方法,另一种方法是实现一个字典,其中键是要删除的字符的索引,值是字符本身。对于此方法,您需要遍历整个文件一次以构建此字典,然后再次迭代以重新添加它们。 示例代码...

tracker = dict()
punct=['?', ':', ';', ',', '.', '!','"','/']
words = list("If it walks like a duck, and it quacks like a duck, then it must be a duck. I love python!")
print("".join(words))
# If it walks like a duck, and it quacks like a duck, then it must be a duck. I love python!
# Removing the punct. 
i = 0
while i < len(words): 
    if words[i] in punct:
        tracker[i+len(tracker.keys())] = words[i]
        words.pop(i)
    i+=1

print("".join(words))
# If it walks like a duck and it quacks like a duck then it must be a duck I love python
# Adding the punct back 
for k,v in tracker.items():
        words = words[:k] +  [v] + words[k:]
print("".join(words))
# If it walks like a duck, and it quacks like a duck, then it must be a duck. I love python!

相关内容

最新更新