Чтение файла. Регулярные выражения - PullRequest
0 голосов
/ 11 июня 2019

Существует файл C: \ Density.txt, в который периодически записываются четыре значения. Для обработки и дальнейшего анализа мне нужен только четвертый знак, Плотность:.

Подход к обработке файлов заключается в следующем. Есть ли возможность получить значение Density: с помощью регулярных выражений?

Пример файла Английский:

Solid density
Mass in the air:
           23.384 (1) g
Mass in liquid:
           23.383 (3) g
Solid volume:
               0.001 cm3
 
  Density:
          1111.586 g / cm3
           ==============
Solid density
Mass in the air:
           23.384 (1) g
Mass in liquid:
           23.383 (3) g
Solid volume:
               0.001 cm3
 
  Density:
          1112.586 g / cm3
           ==============
Solid density
Mass in the air:
           23.384 (1) g
Mass in liquid:
           23.383 (3) g
Solid volume:
               0.001 cm3
 
  Density:
          1113.586 g / cm3
           ==============

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

$ScalesM = [System.io.File]::Open('C:\DensityNT.txt', 'Open', 'ReadWrite', 'None') 
$OutFile = [System.io.File]::Open('C:\\InfinityDensity.txt', 'append', 'Write', 'None')

            $ScalesM2 = New-Object System.IO.StreamReader($ScalesM)
            $text = $text + $ScalesM2.ReadToEnd()
  # Next sring Give my the Error -
$text = ($text | Select-String -Pattern "[0-9\.].+?(?=( g\/cm3))" -AllMatches).Matches.Value 

            $data = $enc.GetBytes($text) 
            $OutFile.write($data,0,$data.length) 


            $ScalesM.SetLength(0)
            $ScalesM.Close()
            $OutFile.Close()

Ответы [ 3 ]

1 голос
/ 11 июня 2019

Вы можете использовать положительный прогноз:

$Text = Get-Content C:\Density.txt
($Text | Select-String -Pattern "[0-9\.].+?(?=( g \/ cm3))" -AllMatches).Matches.Value

Вывод:

1111.586 
1112.586 
1113.586
0 голосов
/ 14 июня 2019

Спасибо за помощь. Полное разрешение ниже:

$TValue = ""
$enc    = [system.Text.Encoding]::UTF8
$NL     = [System.Environment]::NewLine

while ($countI=1) {

try {
    $ScalesM = [System.io.File]::Open('C:\IN.txt', 'Open', 'ReadWrite', 'None') 
    $OutFile = [System.io.File]::Open('C:\OUT.txt', 'append', 'Write', 'None')

    $ScalesM2 = New-Object System.IO.StreamReader($ScalesM)
    $text = $ScalesM2.ReadToEnd()

         [regex]::matches($text, ':\s*(\d+\.?\d*)\s+g\s*/\s*cm3') | %{
        $TValue = $TValue +  $_.Groups[1].value + $NL
                                                                  }

        $data = $enc.GetBytes($TValue) 
        $OutFile.write($data,0,$data.Length)
        $ScalesM.SetLength(0) 
        $ScalesM.Close()
        $OutFile.Close()

        Wait-Event -Timeout 1

    }

catch {
    echo ″Some error was found.″
            $ScalesM.Close()
            $OutFile.Close()
    Wait-Event -Timeout 0.5
}

}
0 голосов
/ 11 июня 2019

Это должно сделать это:

$txt = Get-Content 'PATH TO THE DENSITY.TXT FILE'
$regex = [regex] '(?m)Density:\s+(?<density>.+)'
$match = $regex.Match($txt)
while ($match.Success) {
    $match.Groups['density'].Value
    $match = $match.NextMatch()
} 

выведет

1111.586 g / cm3
1112.586 g / cm3
1113.586 g / cm3


Обновление

На моей машине регулярное выражение со значением Плотность: не работало.Поскольку значения, которые вы хотите получить, заканчиваются на g/cm3 или g / cm3, приведенный ниже код получает их для версий на английском и русском языках:

$txt = Get-Content 'PATH TO THE DENSITY.TXT FILE' -Encoding UTF8
$regex  = [regex]'(?<density>\d+(?:\.\d+)?\s+g\s*/\s*cm3)'
$match = $regex.Match($txt)
$result = while ($match.Success) {
    $match.Groups['density'].Value
    $match = $match.NextMatch()
} 

# output on screen:
$result

# output to file
$result | Set-Content 'D:\Densities.txt'

Сведения о регулярном выражении:

(?<density>     Match the regular expression below and capture its match into backreference with name “density”
   \d           Match a single digit 0..9
      +         Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   (?:          Match the regular expression below
      \.        Match the character “.” literally
      \d        Match a single digit 0..9
         +      Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   )?           Between zero and one times, as many times as possible, giving back as needed (greedy)
   \s           Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
      +         Between one and unlimited times, as many times as possible, giving back as needed (greedy)
   g            Match the character “g” literally
   \s           Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
      *         Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   \/           Match the character “/” literally
   \s           Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
      *         Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   cm3          Match the characters “cm3” literally
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...