ASCII가 아닌 문자를 제거하고 Python을 사용하여 마침표와 공백을 남기려면 어떻게해야합니까?
.txt 파일로 작업하고 있습니다. ASCII가 아닌 문자가없는 파일의 텍스트 문자열을 원합니다. 그러나 공백과 마침표를 남기고 싶습니다. 현재 나는 그것들도 벗겨 내고있다. 코드는 다음과 같습니다.
def onlyascii(char):
if ord(char) < 48 or ord(char) > 127: return ''
else: return char
def get_my_string(file_path):
f=open(file_path,'r')
data=f.read()
f.close()
filtered_data=filter(onlyascii, data)
filtered_data = filtered_data.lower()
return filtered_data
공백과 마침표를 남기려면 onlyascii ()를 어떻게 수정해야합니까? 너무 복잡하지 않다고 생각하지만 이해할 수 없습니다.
다음 과 같이 string.printable을 사용하여 인쇄 할 수없는 문자열의 모든 문자를 필터링 할 수 있습니다 .
>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'
내 컴퓨터의 string.printable에는 다음이 포함됩니다.
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c
편집 : Python 3에서 필터는 iterable을 반환합니다. 문자열을 다시 얻는 올바른 방법은 다음과 같습니다.
''.join(filter(lambda x: x in printable, s))
다른 코덱으로 쉽게 변경하는 방법은 encode () 또는 decode ()를 사용하는 것입니다. 귀하의 경우 ASCII로 변환하고 지원되지 않는 모든 기호를 무시하려고합니다. 예를 들어 스웨덴 문자 å는 ASCII 문자가 아닙니다.
>>>s = u'Good bye in Swedish is Hej d\xe5'
>>>s = s.encode('ascii',errors='ignore')
>>>print s
Good bye in Swedish is Hej d
편집하다:
Python3 : str-> 바이트-> str
>>>"Hej då".encode("ascii", errors="ignore").decode()
'hej d'
Python2 : 유니 코드-> str-> 유니 코드
>>> u"hej då".encode("ascii", errors="ignore").decode()
u'hej d'
Python2 : str-> unicode-> str (역순으로 디코딩 및 인코딩)
>>> "hej d\xe5".decode("ascii", errors="ignore").encode()
'hej d'
@artfulrobot에 따르면 이것은 필터 및 람다보다 빠릅니다.
re.sub(r'[^\x00-\x7f]',r'', your-non-ascii-string)
귀하의 질문은 모호합니다. 처음 두 문장을 함께 사용하면 공백과 "마침표"가 ASCII가 아닌 문자라고 믿습니다. 이것은 올바르지 않습니다. ord (char) <= 127과 같은 모든 문자는 ASCII 문자입니다. 예를 들어, 함수는 이러한 문자! "# $ % & \ '() * +,-. /를 제외하지만 [] {}와 같은 다른 문자를 포함합니다.
뒤로 물러서서 조금 생각하고 질문을 편집하여 ASCII라는 단어를 언급하지 않고 수행하려는 작업과 ord (char)> = 128과 같은 문자를 무시할 수 있다고 생각하는 이유를 알려주십시오. 또한 : 어떤 버전의 Python? 입력 데이터의 인코딩은 무엇입니까?
Please note that your code reads the whole input file as a single string, and your comment ("great solution") to another answer implies that you don't care about newlines in your data. If your file contains two lines like this:
this is line 1
this is line 2
the result would be 'this is line 1this is line 2'
... is that what you really want?
A greater solution would include:
- a better name for the filter function than
onlyascii
recognition that a filter function merely needs to return a truthy value if the argument is to be retained:
def filter_func(char): return char == '\n' or 32 <= ord(char) <= 126 # and later: filtered_data = filter(filter_func, data).lower()
If you want printable ascii characters you probably should correct your code to:
if ord(char) < 32 or ord(char) > 126: return ''
this is equivalent, to string.printable
(answer from @jterrace), except for the absence of returns and tabs ('\t','\n','\x0b','\x0c' and '\r') but doesnt correspond to the range on your question
You may use the following code to remove non-English letters:
import re
str = "123456790 ABC#%? .(朱惠英)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)
This will return
123456790 ABC#%? .()
Working my way through Fluent Python (Ramalho) - highly recommended. List comprehension one-ish-liners inspired by Chapter 2:
onlyascii = ''.join([s for s in data if ord(s) < 127])
onlymatch = ''.join([s for s in data if s in
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'])
'program tip' 카테고리의 다른 글
404를 어떻게 잡을 수 있습니까? (0) | 2020.09.15 |
---|---|
Python : AZ 범위를 인쇄하는 방법? (0) | 2020.09.15 |
div에 jQuery "깜박이는 하이라이트"효과? (0) | 2020.09.15 |
그립을 통해서만 크기를 조정할 수있는 테두리없이 WPF 창을 만드는 방법은 무엇입니까? (0) | 2020.09.15 |
chrome 또는 firefox를 사용하여 javascript에서 console.trace ()의 결과를 얻는 방법은 무엇입니까? (0) | 2020.09.14 |