문자열에서 구두점을 제거하려면 어떻게해야합니까?
이 질문의 30 초 안에 답변을 희망하는 부분에 대해서는 특별히 C #을 찾고 있습니다.
그러나 일반적인 경우 모든 언어에서 구두점을 제거하는 가장 좋은 방법은 무엇입니까?
추가해야합니다. 이상적으로는 솔루션에서 가능한 모든 구두점을 열거 할 필요가 없습니다.
관련 항목 : Python에서 구두점 제거
new string(myCharCollection.Where(c => !char.IsPunctuation(c)).ToArray());
왜 단순히 :
string s = "sxrdct? fvzguh, bij."; var sb = new StringBuilder (); foreach (s의 char c) { if (! char.IsPunctuation (c)) sb.Append (c); } s = sb.ToString ();
RegEx의 사용은 일반적으로 간단한 char 작업보다 느립니다. 그리고 그 LINQ 작업은 나에게 과잉처럼 보입니다. 그리고 .NET 2.0에서는 이러한 코드를 사용할 수 없습니다.
"최고"가 "가장 단순하다"라는 것을 의미한다고 가정하면 다음과 같이 사용하는 것이 좋습니다.
String stripped = input.replaceAll("\\p{Punct}+", "");
이 예제는 Java 용 이지만 충분히 현대적인 모든 Regex 엔진은이를 지원해야합니다 (또는 이와 유사한 것).
편집 : 유니 코드 인식 버전은 다음과 같습니다.
String stripped = input.replaceAll("\\p{P}+", "");
첫 번째 버전은 ASCII에 포함 된 구두점 문자 만 살펴 봅니다.
의도, 가장 읽기 쉬운 (IMHO) 및 최고 성능을 설명합니다.
s = s.StripPunctuation();
구현:
public static class StringExtension
{
public static string StripPunctuation(this string s)
{
var sb = new StringBuilder();
foreach (char c in s)
{
if (!char.IsPunctuation(c))
sb.Append(c);
}
return sb.ToString();
}
}
이것은 게시 된 묶음 중 최고 성능이었던 Hades32의 알고리즘을 사용하고 있습니다.
regex.replace 메소드를 사용할 수 있습니다.
replace(YourString, RegularExpressionWithPunctuationMarks, Empty String)
이것은 문자열을 반환하므로 메서드는 다음과 같습니다.
string s = Regex.Replace("Hello!?!?!?!", "[?!]", "");
원하는 경우 "[?!]"를 좀 더 정교한 것으로 바꿀 수 있습니다.
(\p{P})
구두점을 찾을 수 있습니다.
이 스레드는 너무 오래되었지만 더 우아한 (IMO) 솔루션을 게시하지 않는 것이 좋습니다.
string inputSansPunc = input.Where(c => !char.IsPunctuation(c)).Aggregate("", (current, c) => current + c);
LINQ sans WTF입니다.
GWLlosa의 아이디어를 바탕으로 저는 매우 추악한 것을 생각 해낼 수 있었지만 작업했습니다.
string s = "cat!"; s = s.ToCharArray().ToList<char>() .Where<char>(x => !char.IsPunctuation(x)) .Aggregate<char, string>(string.Empty, new Func<string, char, string>( delegate(string s, char c) { return s + c; }));
가장 간단한 방법은 string.replace를 사용하는 것입니다.
내가 상상하는 다른 방법은 regex.replace이고 그 안에 모든 적절한 구두점이있는 정규식을 갖는 것입니다.
이것을 토큰 화 텍스트에 사용하려면 다음을 사용할 수 있습니다.
new string(myText.Select(c => char.IsPunctuation(c) ? ' ' : c).ToArray())
다음은 linq를 사용하는 약간 다른 접근 방식입니다. 나는 AviewAnew를 좋아하지만 이것은 Aggregate를 피합니다.
string myStr = "Hello there..';,]';';., Get rid of Punction";
var s = from ch in myStr
where !Char.IsPunctuation(ch)
select ch;
var bytes = UnicodeEncoding.ASCII.GetBytes(s.ToArray());
var stringResult = UnicodeEncoding.ASCII.GetString(bytes);
$newstr=ereg_replace("[[:punct:]]",'',$oldstr);
나는 동일한 문제에 직면했고 모든 단일 검사에 대해 IsPunctuation을 호출하는 것이 성능에 미치는 영향에 대해 걱정했습니다.
이 게시물을 찾았습니다 : http://www.dotnetperls.com/char-ispunctuation .
줄 건너 뛰기 : char.IsPunctuation은 또한 ASCII 위에서 유니 코드를 처리합니다. 이 방법은 제어 문자를 포함한 여러 문자와 일치합니다. 정의에 따르면이 방법은 무겁고 비용이 많이 듭니다.
The bottom line is that I finally didn't go for it because of its performance impact on my ETL process.
I went for the custom implemetation of dotnetperls.
And jut FYI, here is some code deduced from the previous answers to get the list of all punctuation characters (excluding the control ones):
var punctuationCharacters = new List<char>();
for (int i = char.MinValue; i <= char.MaxValue; i++)
{
var character = Convert.ToChar(i);
if (char.IsPunctuation(character) && !char.IsControl(character))
{
punctuationCharacters.Add(character);
}
}
var commaSeparatedValueOfPunctuationCharacters = string.Join("", punctuationCharacters);
Console.WriteLine(commaSeparatedValueOfPunctuationCharacters);
Cheers, Andrew
#include<string>
#include<cctype>
using namespace std;
int main(int a, char* b[]){
string strOne = "H,e.l/l!o W#o@r^l&d!!!";
int punct_count = 0;
cout<<"before : "<<strOne<<endl;
for(string::size_type ix = 0 ;ix < strOne.size();++ix)
{
if(ispunct(strOne[ix]))
{
++punct_count;
strOne.erase(ix,1);
ix--;
}//if
}
cout<<"after : "<<strOne<<endl;
return 0;
}//main
For long strings I use this:
var normalized = input
.Where(c => !char.IsPunctuation(c))
.Aggregate(new StringBuilder(),
(current, next) => current.Append(next), sb => sb.ToString());
performs much better than using string concatenations (though I agree it's less intuitive).
참고URL : https://stackoverflow.com/questions/421616/how-can-i-strip-punctuation-from-a-string
'Development Tip' 카테고리의 다른 글
애플리케이션에서 가상화 된 OS를 감지 하시겠습니까? (0) | 2020.11.19 |
---|---|
응용 프로그램 풀 다시 시작 (재활용) (0) | 2020.11.19 |
Win7 64 비트, Python 2.6.4에 PIL (Python Imaging Library) 설치 (0) | 2020.11.19 |
부분보기에 매개 변수 전달 (0) | 2020.11.19 |
CSV 형식의 mysqldump (0) | 2020.11.19 |