ASC가 아닌 것을 제거하려면 어떻게 해야 합니까?II 문자는 마침표와 공백을 남깁니다.
.txt 파일로 작업 중입니다.ASC가 아닌 파일의 텍스트 문자열을 원합니다.II 캐릭터.하지만, 저는 공백과 마침표를 남기고 싶습니다.지금은 그것들도 벗기고 있습니다.코드는 다음과 같습니다.
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
공백과 마침표를 남기려면 어떻게 asci()만 수정해야 합니까?너무 복잡하지는 않을 것 같은데 이해가 안 되네요.
다음과 같이 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에서 필터는 반복 가능한 값을 반환합니다.문자열을 다시 가져오는 올바른 방법은 다음과 같습니다.
''.join(filter(lambda x: x in printable, s))
다른 코덱으로 쉽게 변경할 수 있는 방법은 encode() 또는 decode()를 사용하는 것입니다.이 경우 ASCII로 변환하고 지원되지 않는 모든 기호를 무시하려고 합니다.예를 들어 스웨덴 문자 ▁is는 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에 따르면 필터 및 람다보다 빨라야 합니다.
import re
re.sub(r'[^\x00-\x7f]',r'', your-non-ascii-string)
여기에서 더 많은 예를 참조하십시오. 비 ASC 교체단일 공백이 있는 II 문자
다음 코드를 사용하여 영어가 아닌 문자를 제거할 수 있습니다.
import re
str = "123456790 ABC#%? .(朱惠英)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)
반환됩니다.
123456790 ABC#%? .()
질문이 모호합니다. 처음 두 문장을 함께 사용하면 공간과 "주기"가 ASC가 아니라고 믿는다는 것을 의미합니다.II 캐릭터.이것은 올바르지 않습니다.ord(char) <= 127과 같은 모든 문자는 ASCII 문자입니다.예를 들어 함수에서 이러한 문자 "#$%&\'()*,-/를 제외하지만 []{}와 같은 여러 문자를 포함합니다.
ASCII라는 단어를 언급하지 않고, 당신이 무엇을 하려고 하는지, 그리고 왜 그런 chars >(char) >= 128은 무시할 수 없다고 생각하는지 우리에게 알려주기 위해 뒤로 물러나 생각하고, 당신의 질문을 편집해주세요.또한: 어떤 버전의 파이썬입니까?입력 데이터의 인코딩은 무엇입니까?
코드는 전체 입력 파일을 단일 문자열로 읽으며, 다른 답변에 대한 코멘트("훌륭한 솔루션")는 데이터의 새 줄에 관심이 없음을 의미합니다.파일에 다음과 같은 두 줄이 포함된 경우:
this is line 1
this is line 2
는 결는과일 입니다.'this is line 1this is line 2'
그게 당신이 정말 원하는 겁니까?
더 나은 솔루션은 다음과 같습니다.
- 은 터기능대나이름은보다 더 .
onlyascii
인수를 유지하려면 필터 함수가 진실 값만 반환하면 된다는 인식:
def filter_func(char): return char == '\n' or 32 <= ord(char) <= 126 # and later: filtered_data = filter(filter_func, data).lower()
Fluent Python(라말호)을 통해 내 방식대로 작업 - 강력 추천.제2장에서 영감을 얻은 이해력을 한 줄로 나열합니다.
onlyascii = ''.join([s for s in data if ord(s) < 127])
onlymatch = ''.join([s for s in data if s in
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'])
인쇄 가능한 ASCII 문자를 사용하려면 코드를 다음으로 수정해야 합니다.
if ord(char) < 32 or ord(char) > 126: return ''
이은것동, 합니다등와다와 같습니다.string.printable
(@), 및 경우('\및에 대한 (@jterrace의 경우\t',\n,\x0b',\x0c', '\r')와
이것은 ASCII 문자와 정리 코드를 가져오는 가장 좋은 방법입니다. 가능한 모든 오류를 확인합니다.
from string import printable
def getOnlyCharacters(texts):
_type = None
result = ''
if type(texts).__name__ == 'bytes':
_type = 'bytes'
texts = texts.decode('utf-8','ignore')
else:
_type = 'str'
texts = bytes(texts, 'utf-8').decode('utf-8', 'ignore')
texts = str(texts)
for text in texts:
if text in printable:
result += text
if _type == 'bytes':
result = result.encode('utf-8')
return result
text = '�Ahm�����ed Sheri��'
result = getOnlyCharacters(text)
print(result)
#input --> �Ahm�����ed Sheri��
#output --> Ahmed Sheri
언급URL : https://stackoverflow.com/questions/8689795/how-can-i-remove-non-ascii-characters-but-leave-periods-and-spaces
'code' 카테고리의 다른 글
웹 작업자가 할 수 없는 서비스 작업자가 할 수 있는 일은 무엇입니까? (0) | 2023.07.27 |
---|---|
하이픈/대시를 사용한 MariaDB 전체 텍스트 검색 (0) | 2023.07.27 |
파이썬에서 좋은 __hash__ 함수를 구현하는 방법 (0) | 2023.07.22 |
Spring Security oauth2 클라이언트 - Twitter 문제 (0) | 2023.07.22 |
요구사항 사용 방법.txt: 파이썬 프로젝트에 모든 종속성을 설치합니다. (0) | 2023.07.22 |