python - 如何从单词中删除一个字符,但前提是它位于开头或结尾?

标签 python

def data_from_file(filename):

    list1 = []

    infile = open(filename, 'r', encoding="utf-8")

    lines = infile.read().split()
    lines = " ".join(lines)
    lines1 = lines.replace("." , "")
    lines2 = lines1.replace(",", "")
    lines3 = lines2.replace("\n", "")
    lines4 = lines3.replace("\"", "")
    lines5 = lines4.replace("\\", "")
    lines6 = lines5.replace("\"", "")
    lines7 = lines6.replace(":", "")
    lines8 = lines7.replace(";", "")

    lines9 = lines8.split()

    for i in lines9:
        if i.isalpha():
            list1.append(i)
    return list1

嗨,这里是代码新手,

基本上我需要做的是从某个文件中读取数据。然后我需要删除诸如 ("; : . ,\n ' ) 之类的字符,但前提是它们位于单词的开头或结尾。目前我的程序删除了这些字符的每个实例。例如,我希望能够将“汽车”变成汽车,但汽车仍旧是汽车

程序的下一部分只涉及选择每个位置都有字母数字字符的单词。这部分工作完美。

如有任何帮助,我们将不胜感激。

最佳答案

str.strip做你想做的:

>>> 'potato'.strip('o')
'potat'

还有str.lstripstr.rstrip 如果你只想分别从左边或右边起飞。

关于python - 如何从单词中删除一个字符,但前提是它位于开头或结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23518088/

相关文章:

python - django-channels 是否适合实时游戏?

python - 从二维数组python中获取唯一项

python - 在进程池之间共享字典和数组

python - 您可以使用 ctypes 通过内存 id 将对象传递给 celery 任务吗?

Python多处理池在加入时挂起?

python - 有效地按降序对numpy数组进行排序?

python - 从 txt 文件创建 heatmap2d

python - 使用 Pandas 转换年度数据

python - 将自定义链接添加到 hudson 项目页面

python - 如何使用排序的键列表对 OrderedDict 进行排序?