File size: 2,280 Bytes
4b07a4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60


## Cleaning

Unlike the original dataset, the `func_code_string` column was updated to remove any comments and keep just the code.
The original version can still be found in the `whole_func_string`.

```py
import re

def remove_comments_docstrings(code, language):
    if language == 'python':
        # Remove docstrings
        code = re.sub(r'"""(.*?)"""', '', code, flags=re.DOTALL)
        code = re.sub(r"'''(.*?)'''", '', code, flags=re.DOTALL)
        # Remove comments
        code = re.sub(r'#.*', '', code)
    elif language == 'java' or language == 'javascript':
        # Remove multiline comments
        code = re.sub(r'/\*.*?\*/', '', code, flags=re.DOTALL)
        # Remove single line comments
        code = re.sub(r'//.*', '', code)
    elif language == 'go':
        # Similar to Java/Javascript
        code = re.sub(r'/\*.*?\*/', '', code, flags=re.DOTALL)
        code = re.sub(r'//.*', '', code)
    elif language == 'ruby':
        # Remove multiline comments
        code = re.sub(r'=begin.*?=end', '', code, flags=re.DOTALL)
        # Remove single line comments
        code = re.sub(r'#.*', '', code)
    elif language == 'php':
        # Remove multiline comments
        code = re.sub(r'/\*.*?\*/', '', code, flags=re.DOTALL)
        # Remove single line and hash comments
        code = re.sub(r'//.*', '', code)
        code = re.sub(r'#.*', '', code)
    return code.strip()
```

The validity of that snippet can be tested with the following example:

```py
# Example DataFrame
import pandas as pd
example = {
  'language': ['python', 'java', 'javascript', 'go', 'ruby', 'php'],
  'func_code_string': [
    '"""Example docstring""" def foo(): # This is a comment\n    return 1',
    '/** Java doc */ public class Test { // Comment\n public void method() {} }',
    '/* JS doc */ function test() { // Comment\n return true; }',
    '/* Go doc */ package main // Import comment\nimport "fmt"',
    '=begin Ruby doc =end def foo # Comment\n 1 + 1 end',
    '<?php /* PHP doc */ // Comment\necho "Hello"; # Another comment ?>'
]}
example_df = pd.DataFrame(example)

example_df['cleaned_code'] = example_df.apply(lambda x: remove_comments_docstrings(x['func_code_string'], x['language']), axis=1)
print(example_df[['language', 'cleaned_code']])
```