函数以消除python中的delimeters

函数以消除python中的delimeters,python,python-3.x,Python,Python 3.x,我有一个函数,用户在其中传递一个文件和一个字符串,代码应该去掉特定的delimeters。我很难完成循环代码并删除每个替换项的部分。我会把代码贴在下面 def forReader(filename): try: # Opens up the file file = open(filename , "r") # Reads the lines in the file read = file.readlines() # closes the files

我有一个函数,用户在其中传递一个文件和一个字符串,代码应该去掉特定的delimeters。我很难完成循环代码并删除每个替换项的部分。我会把代码贴在下面

def forReader(filename):
try:
    # Opens up the file
    file = open(filename , "r")
    # Reads the lines in the file
    read = file.readlines()
    # closes the files
    file.close()
        # loops through the lines in the file
    for sentence in read:
            # will split each element by a spaace
            line = sentence.split()
    replacements = (',', '-', '!', '?' '(' ')' '<' ' = ' ';')
    # will loop through the space delimited line and get rid of
    # of the replacements
    for sentences in line:




# Exception thrown if File does not exist
except FileExistsError:
    print('File is not created yet')


forReader("mo.txt")
运行filemo.txt后,我希望输出如下所示
对于int i

,这里有一种使用regex实现的方法。首先,我们创建一个由所有分隔符组成的模式,小心地将它们转义,因为其中一些字符在正则表达式中具有特殊的含义。然后我们可以使用re.sub将每个分隔符替换为空字符串。这个过程会给我们留下两个或多个相邻的空间,然后我们需要用单个空间来替换它们

pythonre模块允许我们编译经常使用的模式。从理论上讲,这可以使它们更有效,但最好用真实数据测试这种模式,看看它是否真的有用

import re

delimiters = ',-!?()<=;'

# Make a pattern consisting of all the delimiters
pat = re.compile('|'.join(re.escape(c) for c in delimiters))

s = 'for ( int i;'

# Remove the delimiters
z = pat.sub('', s)

#Clean up any runs of 2 or more spaces
z = re.sub(r'\s{2,}', ' ', z)
print(z)

我想这是家庭作业。你可以使用正则表达式吗?哈哈,不,这不是家庭作业。这实际上是我和一个朋友正在做的一个附带项目。是的,正则表达式很好。我不熟悉python,这就是为什么我在这方面遇到困难的原因。在这种情况下,您可以使用。一个示例将非常有用@PM2Ringstr.maketrans?您是一个救生员。如果我在这件事上还有什么问题,我可以问你吗?@jsilva很乐意帮忙。如果您对这段代码有进一步的疑问,可以在这里发表评论。但是,如果您有一个与上述代码没有直接关系的新问题,那么只需问一个新问题:好的,现在我想做的是,在取出delimeters之后,检查一个特定的单词是否在我们的新列表中。我该怎么做呢?例如,我试着做一个基本的循环,遍历新列表并检查单词,但没有luck@jsilva这是一个新问题但是如果你只想测试一个单词,你可以使用in操作符来做类似的事情。例如,s=‘这是一个测试句’;在s中打印“测试”。然而,这也会发现嵌入在其他单词中的部分单词,例如s中的“sent”是真的。您可能不希望这样做。@jsilva安全的方法是将清理后的字符串拆分为一个单词列表,然后您可以安全地使用它。例如,在s.split中的“test”
import re

delimiters = ',-!?()<=;'

# Make a pattern consisting of all the delimiters
pat = re.compile('|'.join(re.escape(c) for c in delimiters))

s = 'for ( int i;'

# Remove the delimiters
z = pat.sub('', s)

#Clean up any runs of 2 or more spaces
z = re.sub(r'\s{2,}', ' ', z)
print(z)
for int i