似乎应该有一个比以下更简单的方法:
import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
Run Code Online (Sandbox Code Playgroud)
在那儿?
我正在尝试使用Python从字符串中删除特定字符.这是我现在正在使用的代码.不幸的是它似乎对字符串没有任何作用.
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
filter,map并且reduce在Python 2中完美地工作.这是一个例子:
>>> def f(x):
return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x):
return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def add(x,y):
return x+y
>>> reduce(add, range(1, 11))
55
Run Code Online (Sandbox Code Playgroud)
但是在Python 3中,我收到以下输出:
>>> filter(f, range(2, 25))
<filter object at 0x0000000002C14908>
>>> map(cube, range(1, 11))
<map object at 0x0000000002C82B70> …Run Code Online (Sandbox Code Playgroud) 我想使用.translate()方法从文本文件中删除所有标点符号.它似乎在Python 2.x下运行良好,但在Python 3.4下似乎没有做任何事情.
我的代码如下,输出与输入文本相同.
import string
fhand = open("Hemingway.txt")
for fline in fhand:
fline = fline.rstrip()
print(fline.translate(string.punctuation))
Run Code Online (Sandbox Code Playgroud)