Лучший способ убрать пунктуацию из строки в Python - PullRequest
512 голосов
/ 05 ноября 2008

Кажется, что должен быть более простой способ, чем:

import string
s = "string. With. Punctuation?" # Sample string 
out = s.translate(string.maketrans("",""), string.punctuation)

Есть?

Ответы [ 24 ]

1 голос
/ 05 ноября 2008

Выполните поиск и замену, используя функции регулярных выражений, как показано здесь. . Если вам приходится многократно выполнять операцию, вы можете хранить скомпилированную копию шаблона регулярного выражения (пунктуации), что немного ускорит процесс.

0 голосов
/ 17 января 2017

Это как изменить наши документы в верхний регистр или строчные буквы.

print('@@@@This is lower case@@@@')

with open('students.txt','r')as myFile:

    str1=myFile.read()
    str1.lower()
print(str1.lower())

print('*****This is upper case****')

with open('students.txt','r')as myFile:

    str1=myFile.read()

    str1.upper()

print(str1.upper())
0 голосов
/ 05 января 2017

Удалить стоп-слова из текстового файла, используя Python

print('====THIS IS HOW TO REMOVE STOP WORS====')

with open('one.txt','r')as myFile:

    str1=myFile.read()

    stop_words ="not", "is", "it", "By","between","This","By","A","when","And","up","Then","was","by","It","If","can","an","he","This","or","And","a","i","it","am","at","on","in","of","to","is","so","too","my","the","and","but","are","very","here","even","from","them","then","than","this","that","though","be","But","these"

    myList=[]

    myList.extend(str1.split(" "))

    for i in myList:

        if i not in stop_words:

            print ("____________")

            print(i,end='\n')
0 голосов
/ 06 апреля 2013

Мне нравится использовать такую ​​функцию:

def scrub(abc):
    while abc[-1] is in list(string.punctuation):
        abc=abc[:-1]
    while abc[0] is in list(string.punctuation):
        abc=abc[1:]
    return abc
...