2014-01-12 2 views
0

Скажем, у меня есть текстовый файл test.txt в диске C.Разделить строки на слова, а затем сохранить как новый файл

On the face of things, we seem to be merely talking about text-based files, containing only 
the letters of the English Alphabet (and the occasional punctuation mark). 
On deeper inspection, of course, this isn't quite the case. What this site 
offers is a glimpse into the history of writers and artists bound by the 128 
characters that the American Standard Code for Information Interchange (ASCII) 
allowed them. The focus is on mid-1980's textfiles and the world as it was then, 
but even these files are sometime retooled 1960s and 1970s works, and offshoots 
of this culture exist to this day. 

Я хочу разбить все строки на слова, а затем сохранить их как новый файл. В новом файле каждая строка содержит только одно слово.

Таким образом, новый файл будет:

 On 
     the 
     face 
     of 
     things 
     we 
     seem 
     to 
     .... 

Ограничитель представляет собой белое пространство и пропустите все знаки препинания.

+2

Сделали вы какие-либо attmpt, чтобы решить эту проблему самостоятельно? Можете ли вы поделиться тем, что вы пробовали, и каковы были результаты? – mjolinor

+0

Я не силен на powershell, я использовал C#, но код не кратким. –

ответ

2

Вы даже не пробовали. В следующий раз я голосую за закрытый вопрос. Powershell использует 99% синтаксиса C# и «все» .Net-классы доступны, поэтому, если вы знаете C#, вы зашли далеко в PowerShell, используя 5 минут в Google и попробуйте некоторые команды.

#create array 
$words = @() 

#read file 
$lines = [System.IO.File]::ReadAllLines("C:\Users\Frode\Desktop\in.txt") 

#split words 
foreach ($line in $lines) { 
    $words += $line.Split(" ,.", [System.StringSplitOptions]::RemoveEmptyEntries) 
} 

#save words 
[System.IO.File]::WriteAllLines("C:\Users\Frode\Desktop\out.txt", $words) 

В PowerShell можно также сделать это следующим образом:

Get-Content .\in.txt | ForEach-Object { 
    $_.Split(" ,.", [System.StringSplitOptions]::RemoveEmptyEntries) 
} | Set-Content out.txt 
0

Вот решение с использованием регулярных выражений, которые будут:

  • Удалить специальные символы
  • Разбор слова на основе границы слов (\b in regex)

Код:

$Text = @' 
On the face of things, we seem to be merely talking about text-based files, containing only 
the letters of the English Alphabet (and the occasional punctuation mark). 
On deeper inspection, of course, this isn't quite the case. What this site 
offers is a glimpse into the history of writers and artists bound by the 128 
characters that the American Standard Code for Information Interchange (ASCII) 
allowed them. The focus is on mid-1980's textfiles and the world as it was then, 
but even these files are sometime retooled 1960s and 1970s works, and offshoots 
of this culture exist to this day. 
'@; 

# Remove special characters 
$Text = $Text -replace '\(|\)|''|\.|,',''; 
# Match words 
$MatchList = ([Regex]'(?<word>\b\w+\b)').Matches($Text); 
# Get just the text values of the matches 
$WordList = $MatchList | % { $PSItem.Groups['word'].Value; }; 
# Examine the 'Count' of words 
$WordList.Count 

Результат выглядит следующим образом:

$WordList[0..9]; 
On 
the 
face 
of 
things 
we 
seem 
to 
be 
merely 
0

Я бы не беспокоить разделив строку, так как вы пишете результат обратно в файл в любом случае. Просто замените все знаки препинания (и, возможно, круглые скобки, а) с пробелами, замените все подряд пробелы с символом новой строки, и записывать все обратно в файл:

$in = 'C:\test.txt' 
$out = 'C:\test2.txt' 

(Get-Content $in | Out-String) -replace '[.,;:?!()]',' ' -replace '\s+',"`r`n" | 
    Set-Content $out 
1
$Text = @' 
On the face of things, we seem to be merely talking about 
text-based files, containing only the letters of the English Alphabet 
(and the occasional punctuation mark). On deeper inspection, of 
course, this isn't quite the case. What this site offers is a glimpse 
into the history of writers and artists bound by the 128 characters 
that the American Standard Code for Information Interchange (ASCII) 
allowed them. The focus is on mid-1980's textfiles and the world as it 
was then, but even these files are sometime retooled 1960s and 1970s 
works, and offshoots of this culture exist to this day. 
'@ 

[regex]::split($Text, ‘\W+’) 
+0

Хороший ответ, но для некоторых слов типа «нет» он будет разделяться на апострофе. Это кажется менее желательным результатом, поскольку «isn» и «t» не являются словами. В моем ответе я использовал регулярное выражение, чтобы сначала выделить все специальные символы, а затем совместить слова после этого. –

+0

Хорошая точка. Трансформация не имеет проблем. Проблемная проблема. Это может быть больше, чем регулярное выражение. –

+0

Согласовано, у него есть свои проблемы, но он соответствует спецификациям запрашивающего. –

Смежные вопросы