相关疑难解决方法(0)

如何替换所有出现的某些字符?

我正在读一篇csv a:

import csv
import collections
import pdb
import math
import urllib

def do_work():
  a=get_file('c:/pythonwork/cds/cds.csv')
  a=remove_chars(a)
  print a[0:10]

def get_file(start_file): #opens original file, reads it to array
  with open(start_file,'rb') as f:
    data=list(csv.reader(f))
  return (data)

def remove_chars(a):
  badchars=['a','b','c','d']
  for row in a:
    for letter in badchars:
      row[8].replace(letter,'')
  return a
Run Code Online (Sandbox Code Playgroud)

我想['a','b','c','d']用空字符串替换行的第8个元素中出现的所有内容.该remove_chars功能无法正常工作.

有一个更好的方法吗?

python csv

48
推荐指数
1
解决办法
10万
查看次数

从Unicode格式的字符串中删除标点符号

我有一个函数,从字符串列表中删除标点符号:

def strip_punctuation(input):
    x = 0
    for word in input:
        input[x] = re.sub(r'[^A-Za-z0-9 ]', "", input[x])
        x += 1
    return input
Run Code Online (Sandbox Code Playgroud)

我最近修改了我的脚本以使用Unicode字符串,所以我可以处理其他非西方字符.当遇到这些特殊字符并且只返回空的Unicode字符串时,此函数会中断.如何从Unicode格式的字符串中可靠地删除标点符号?

python unicode

40
推荐指数
4
解决办法
2万
查看次数

从Unicode字符串中删除文件名中的禁止字符的最有效方法

我有一个字符串,其中包含我从Web解析的一些数据,并创建一个以此数据命名的文件.

string = urllib.urlopen("http://example.com").read()
f = open(path + "/" + string + ".txt")
f.write("abcdefg")
f.close()
Run Code Online (Sandbox Code Playgroud)

问题是它可能包含以下字符之一:\ / * ? : " < > |.我正在使用Windows,禁止在文件名中使用这些字符.此外,string在Unicode formar中,大多数解决方案都没用.

所以,我的问题是:剥离这些角色的最有效/ pythonic方式是什么?提前致谢!

编辑:文件名是Unicode格式而不是 str!

python string unicode python-2.7

1
推荐指数
2
解决办法
7010
查看次数

Python - 用另一个列表替换字符列表

我有两个清单:

wrong_chars = [
    ['?','?','?','?','?','?'],
    ['?','?','?','?','?','?'],
    ['?','?','?','?','?','?'],
    ['?','?','?','?','?','?'],
]

true_chars = [
    ['?'],
    ['?'],
    ['?'],
    ['?'],
]
Run Code Online (Sandbox Code Playgroud)

对于给定的字符串,我要替换的条目wrong_chars与那些在true_chars.在python中有一个干净的方法吗?

python string unicode

-1
推荐指数
1
解决办法
678
查看次数

标签 统计

python ×4

unicode ×3

string ×2

csv ×1

python-2.7 ×1